我有一张类似于:
的表格user_id | action
1 a1
2 a1
1 a1
3 a1
2 a1
1 a2
2 a2
我必须找出已执行操作a1的用户数,按操作数和a1用户数分组。
例如在上表中,输出应为:
num_users num_action_a1
1 (user: 3) 1
2 (user: 1,2) 2
我尝试了以下查询
select user_id, count(user_id) from table where action = 'a1' group by user_id
我是否必须使用嵌套组?
答案 0 :(得分:1)
使用子查询获取每个用户ID的计数,然后从中选择用户和计数: -
SELECT num_users, GROUP_CONCAT(user_id) AS actual_users , COUNT(*) AS num_action_a1
FROM
(
SELECT user_id, COUNT(*) AS num_users
FROM some_table
WHERE action = 'a1'
GROUP BY user_id
) sub0
GROUP BY num_users