[英]How do I count total of value in one column with different data
I'm a bit confuse how to name my question title.我有点困惑如何命名我的问题标题。
Let say my MySQL database table like this.假设我的 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
I want to group it by UserGroup
and count the UserStatus
.我想按
UserGroup
对它进行分组并计算UserStatus
。
Let me know what is the correct statement to get the result like this让我知道得到这样的结果的正确语句是什么
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
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
You could use case
to count rows that match a condition:您可以使用
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.