I have a mysql query
select sum(duration),app_name,app_id,user_id
from timesheet
where user_id=164
group by app_id
order by sum(duration) desc
limit 5;
The result is
sum(duration), app_name, app_id, user_id
'626919371', 'Idle.exe', '0', '164'
'38220511', 'LockApp.exe', '2204', '164'
'36675000', '', '1', '164'
'27713000', 'LockApp.exe', '8148', '164'
'16698661', 'chrome.exe', '8548', '164'
However I want the top 5 app for every user_id instead of just 164. Can you pelase guide me as to how this can be achieved in a single query. Or do I need to fire it for every individual user
This should work:
SELECT *
FROM (
SELECT *, rank() over (PARTITION BY user_id ORDER BY duration desc) AS rank
FROM (
SELECT user_id, app_id, sum(duration) AS duration
FROM timesheet
GROUP BY user_id, app_id
) sub2
) sub
WHERE rank < 6
If you want the query to always return 5 rows per user (even if there are some top applications with the same rank) replace rank()
with row_number()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.