如何使用不同的数据计算一列中的总值

时间:2011-07-17 15:47:55

标签: mysql sql

我有点混淆如何命名我的问题标题。

让我的MySQL数据库表这样说。 table_group

UserID  UserGroup  UserStatus
------------------------------
1       1          1  
2       1          1 
3       1          2 
4       2          3
5       3          2
6       3          1
7       4          3
9       4          4
10      4          1 

我希望分组 UserGroup计数 UserStatus

让我知道获得结果的正确陈述是什么

UserGroup  Status_1  Status_2  Status_3  Status_4
-------------------------------------------------
1          2          2        0         0
2          0          0        1         0
3          1          1        0         0
4          1          0        1         1

2 个答案:

答案 0 :(得分:1)

SELECT UserGroup, count(UserStatus = 1) as Status_1, count(UserStatus = 2) as Status_2,
                  count(UserStatus = 3) as Status_3, count(UserStatus = 4) as Status_4
FROM table_group GROUP BY UserGroup

答案 1 :(得分:0)

您可以使用case来计算符合条件的行:

select  UserGroup
,       count(case when UserStatus = 1 then 1 end) as Status_1
,       count(case when UserStatus = 2 then 1 end) as Status_2
,       count(case when UserStatus = 3 then 1 end) as Status_3
,       count(case when UserStatus = 4 then 1 end) as Status_4
from    table_group
group by
        UserGroup