SQL to get max value from each group
select * from [table] t1
inner join
(
select track_id, user_id, max(rating) maxRating
from [table]
group by track_id, user_id
) tmp
on t1.track_id = tmp.track_id
and t1.user_id = tmp.user_id
and t1.rating = tmp.maxRating;
Get records with max value for each group of grouped SQL results
There's a super-simple way to do this in mysql:
select *
from (select * from mytable order by `Group`, age desc, Person) x
group by `Group`
This works because in mysql you're allowed to not aggregate non-group-by columns, in which case mysql just returns the first row. The solution is to first order the data such that for each group the row you want is first, then group by the columns you want the value for.
You avoid complicated subqueries that try to find the max()
etc, and also the problems of returning multiple rows when there are more than one with the same maximum value (as the other answers would do)
Note: This is a mysql-only solution. All other databases I know will throw an SQL syntax error with the message "non aggregated columns are not listed in the group by clause" or similar. Because this solution uses undocumented behavior, the more cautious may want to include a test to assert that it remains working should a future version of MySQL change this behavior.
Version 5.7 update:
Since version 5.7, the sql-mode
setting includes ONLY_FULL_GROUP_BY
by default, so to make this work you must not have this option (edit the option file for the server to remove this setting).
Get the row(s) which have the max value in groups using groupby
In [1]: df
Out[1]:
Sp Mt Value count
0 MM1 S1 a 3
1 MM1 S1 n 2
2 MM1 S3 cb 5
3 MM2 S3 mk 8
4 MM2 S4 bg 10
5 MM2 S4 dgd 1
6 MM4 S2 rd 2
7 MM4 S2 cb 2
8 MM4 S2 uyi 7
In [2]: df.groupby(['Mt'], sort=False)['count'].max()
Out[2]:
Mt
S1 3
S3 8
S4 10
S2 7
Name: count
To get the indices of the original DF you can do:
In [3]: idx = df.groupby(['Mt'])['count'].transform(max) == df['count']
In [4]: df[idx]
Out[4]:
Sp Mt Value count
0 MM1 S1 a 3
3 MM2 S3 mk 8
4 MM2 S4 bg 10
8 MM4 S2 uyi 7
Note that if you have multiple max values per group, all will be returned.
Update
On a hail mary chance that this is what the OP is requesting:
In [5]: df['count_max'] = df.groupby(['Mt'])['count'].transform(max)
In [6]: df
Out[6]:
Sp Mt Value count count_max
0 MM1 S1 a 3 3
1 MM1 S1 n 2 3
2 MM1 S3 cb 5 8
3 MM2 S3 mk 8 8
4 MM2 S4 bg 10 10
5 MM2 S4 dgd 1 10
6 MM4 S2 rd 2 7
7 MM4 S2 cb 2 7
8 MM4 S2 uyi 7 7
How to get the maximum value by group
If you know sql this is easier to understand
library(sqldf)
sqldf('select year, max(score) from mydata group by year')
Update (2016-01): Now you can also use dplyr
library(dplyr)
mydata %>% group_by(year) %>% summarise(max = max(score))
Select the row with the maximum value in each group
Here's a data.table
solution:
require(data.table) ## 1.9.2
group <- as.data.table(group)
If you want to keep all the entries corresponding to max values of pt
within each group:
group[group[, .I[pt == max(pt)], by=Subject]$V1]
# Subject pt Event
# 1: 1 5 2
# 2: 2 17 2
# 3: 3 5 2
If you'd like just the first max value of pt
:
group[group[, .I[which.max(pt)], by=Subject]$V1]
# Subject pt Event
# 1: 1 5 2
# 2: 2 17 2
# 3: 3 5 2
In this case, it doesn't make a difference, as there aren't multiple maximum values within any group in your data.
How to find the maximum value within each group and then recode all other values in the group as zero?
You can try this
df %>%
group_by(Id) %>%
mutate(maxByGroup = (which.max(value) == seq_along(value)) * value) %>%
ungroup()
which gives
Id value maxByGroup
<dbl> <dbl> <dbl>
1 1 500 500
2 1 500 0
3 1 500 0
4 2 250 250
5 2 250 0
6 2 250 0
7 3 300 300
8 3 300 0
9 3 300 0
10 4 400 400
11 4 400 0
12 4 400 0
Extract the maximum value within each group in a dataframe
There are many possibilities to do this in R. Here are some of them:
df <- read.table(header = TRUE, text = 'Gene Value
A 12
A 10
B 3
B 5
B 6
C 1
D 3
D 4')
# aggregate
aggregate(df$Value, by = list(df$Gene), max)
aggregate(Value ~ Gene, data = df, max)
# tapply
tapply(df$Value, df$Gene, max)
# split + lapply
lapply(split(df, df$Gene), function(y) max(y$Value))
# plyr
require(plyr)
ddply(df, .(Gene), summarise, Value = max(Value))
# dplyr
require(dplyr)
df %>% group_by(Gene) %>% summarise(Value = max(Value))
# data.table
require(data.table)
dt <- data.table(df)
dt[ , max(Value), by = Gene]
# doBy
require(doBy)
summaryBy(Value~Gene, data = df, FUN = max)
# sqldf
require(sqldf)
sqldf("select Gene, max(Value) as Value from df group by Gene", drv = 'SQLite')
# ave
df[as.logical(ave(df$Value, df$Gene, FUN = function(x) x == max(x))),]
How to find maximum value per group for all rows in SQL?
You need MAX()
window function:
SELECT *,
MAX(value) OVER (PARTITION BY name) "max"
FROM out_pumptable;
See the demo.
Related Topics
Dealing with True, False, Na and Nan
When Should I Use the := Operator in Data.Table
How to Install an R Package from the Source Tarball on Windows
Operator == Inconsistent in Logical Columns in Data.Table
Why Is Allow.Cartesian Required at Times When When Joining Data.Tables with Duplicate Keys
How to Use the Strsplit Function with a Period
Reset Inputs' Button in Shiny App
Remove Duplicates Keeping Entry with Largest Absolute Value
Remove All Rows Where Length of String Is More Than N
Split Up '...' Arguments and Distribute to Multiple Functions
Sort Columns of a Dataframe by Column Name
Count Number of Zeros Per Row, and Remove Rows with More Than N Zeros
How to Deal with "'Somefunction' Is Not an Exported Object from 'Namespace:Somepackage'" Error
How to Connect R with Access Database in 64-Bit Window
How to Connect Two Coordinates with a Line Using Leaflet in R