I need to select top 5 active users based on their total usage in each location.
my table structure is:
id user location date usage
1 1 1 xxx 10
1 2 2 xxx 20
1 1 1 xxx 05
1 2 2 xxx 08
1 3 1 xxx 10
1 3 1 xxx 20
1 1 1 xxx 15
1 1 1 xxx 05
...
...
...
Update: I need to limit this query to return top 5 users for each location
select `location` ,`user`,sum(`usage`) from `table`
group by `location`,`user`
order by `location` ASC,sum(`usage`) DESC
but when I put
limit 0,5
limit does not apply to group by
Update: This query limit user in group but does not sum the usage
select `user`, `location`, `usage`
from
(
select `user`, `location`, `usage`,
(@num:=if(@group = `location`, @num +1, if(@group := `location`, 1,1))) row_number
from `my_table` t
CROSS JOIN (select @num:=0, @group:=null) c
order by `location`, `usage` desc, `user`
) as x
where x.row_number <= 2;
you can check the demo