简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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