如何统计同一个表中每个人的行为?

时间:2015-12-07 15:34:26

标签: mysql group-by concatenation

Mysql表:

(用户,行动)

我可以运行什么查询来获得此结果

用户|每个用户计算action1每个用户计算action2每个用户计算action3

1 个答案:

答案 0 :(得分:1)

SELECT user, count(action1), count(action2),count(action3) GROUP BY user

您可以按用户分组并返回每个操作的记录数。如果您有action type列,则可能需要在计数中使用案例陈述。这看起来像这样:

SELECT user, 
       SUM(CASE WHEN actiontype=1 THEN 1 ELSE 0 END) as Action1Total, 
       SUM(CASE WHEN actiontype=2 THEN 1 ELSE 0 END) as Action2Total,
       SUM(CASE WHEN actiontype=3 THEN 1 ELSE 0 END) as Action3Total
GROUP BY user

您也可以使用COUNT代替。由于默认CASE为空,COUNT不计算null

 COUNT(CASE WHEN actiontype=1 THEN 1 END) as Action1Total