简体   繁体   English

如何计算具有不同数据的一列中的总价值

[英]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.

相关问题 如何计算一列中不同类型的多个总数 - How to count multiple total number of different types in one column 我如何对不同的列求和以获得数组中的总数 - How do i sum different column to get total in array 如何从2个不同的表中进行计数,然后将它们加起来总计? - How do I do a count from 2 different tables then sum them both for a total? 如何获取 MySQL 中一张表中不同列的同名总数? - how can I get the total count of same name of different columns in one table in MySQL? 在mysql中,如何仅选择一列中具有相同值但在另一列中具有不同值的每一行? - In mysql, how do I select ONLY every row that has the same value in one column but different ones in another? python - 如何在python pandas中分组并取一列的计数除以数据框第二列的唯一计数? - How to do group by and take Count of one column divide by count of unique of second column of data frame in python pandas? 用不同的列值计算一列的出现次数? [甲骨文] - Count number of occurrences of one column by a different column value? [Oracle] SQL:如何获得列中不同值的总数? - SQL: How would I get a total count for distinct values in a column? 在 MySQL 中,如果一列与另一列相关,我如何获得组件的总量? - in MySQL how do i get the total amount of components if one column is related to another? 如何在一个SQL中执行两个不同的计数 - How to do two different count in one sql
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM