I have a table logins
with the following schema:
| id | user_id | weekday |
|----|---------|---------|
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 1 | 2 |
...
Weekday is a number from 0 to 6.
I want to get which weekday
has the highest count, for each user_id
in the table.
I tried the following query:
SELECT MAX(num) as max_num, user_id, weekday
FROM (
SELECT COUNT(*) as num, user_id, weekday
FROM logins
GROUP BY user_id, weekday
) C
WHERE user_id = C.user_id AND num = C.num
GROUP BY user_id;
Which gets me weekday = 1
instead of 2
. I think that I shouldn't use a WHERE
clause here, but I couldn't manage to get the correct result.
I've checked other similar questions with no luck, such as:
I created a SQL Fiddle with my example: http://sqlfiddle.com/#!9/e43a71/1