这是我的表x
user | action
1 | A
1 | A
1 | B
1 | C
1 | c
2 | A
2 | B
2 | B
我想知道用户的前2个动作。意思是我希望结果为
1 | A, C
2 | A, B ( or B, A )
我尝试了很多方法,例如
select user , action, COUNT(*) from table where user is NOT NULL group by user, action order by user, COUNT(*);
但我无法得到理想的结果。
答案 0 :(得分:0)
你可以这样做
SELECT user, SUBSTRING_INDEX(GROUP_CONCAT(action ORDER BY rank DESC, action), ',', 2) action
FROM
(
SELECT user, action, COUNT(*) rank
FROM table1
GROUP BY user, action
) q
GROUP BY user
或
SELECT user, GROUP_CONCAT(action) action
FROM
(
SELECT user, action, rank, @n := IF(@g = user, @n + 1, 1) rnum, @g := user
FROM
(
SELECT user, action, COUNT(*) rank
FROM table1
GROUP BY user, action
) q CROSS JOIN (SELECT @n := 0, @g := NULL) i
ORDER BY user, rank DESC, action
) q2
WHERE rnum IN(1, 2)
GROUP BY user
输出:
| USER | ACTION | |------|--------| | 1 | A,C | | 2 | B,A |
这是 SQLFiddle 演示