0

这是我的桌子 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(*);

但我无法得到想要的结果。

4

1 回答 1

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

输出:

| 用户 | 行动 |
|--------|--------|
| 1 | A,C |
| 2 | 乙,甲 |

这是SQLFiddle演示

于 2013-09-24T05:03:48.480 回答