简体   繁体   English

MySQL单一查询来计数多个值

[英]mysql single query to count multiple values

I need single query to count multiple status value... 我需要一个查询来计算多个状态值...

Table

+-------------+------------------+--------+
| ID          | Name             | Status |
+-------------+------------------+--------+
| 50          | Name1            | 1      |
| 49          | Name2            | 2      |
| 50          | Name1            | 1      |
| 49          | Name2            | 1      |
| 50          | Name1            | 2      |
| 50          | Name1            | 2      |
| 50          | Name1            | 3      |
| 50          | Name1            | 3      |
| 50          | Name1            | 1      |
+-------------+------------------+--------+

Expecting Out put: 预期输出:

+-------------+------------------+--------------+--------------+--------------+
| ID          | Name             | Cnt(Status1) | Cnt(Status2) | Cnt(Status3) |
+-------------+------------------+--------------+--------------+--------------+
| 50          | Name1            | 3            | 2            | 2            |
| 49          | Name2            | 1            | 1            | 0            |
+-------------+------------------+--------------+--------------+--------------+

I need query for the above output... 我需要查询上面的输出...

You can use conditional sum to do it 您可以使用条件和来做到这一点

select
id,
Name,
sum(Status=1) as cnt_status1,
sum(Status=2) as cnt_status2,
sum(Status=3) as cnt_status3
from table_name
group by id,Name

I gues this will do the trick: 我想这会成功的:

SELECT
    ID,
    Name,
    COUNT(CASE WHEN Status = 1 THEN 1 ELSE 0 END),
    COUNT(CASE WHEN Status = 2 THEN 1 ELSE 0 END),
    COUNT(CASE WHEN Status = 3 THEN 1 ELSE 0 END)
FROM TABLE
GROUP BY
    ID,
    Name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM