mysql单个查询来计算多个值

时间:2015-03-02 11:00:46

标签: php mysql

我需要单个查询来计算多个状态值...

+-------------+------------------+--------+
| 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      |
+-------------+------------------+--------+

期待输出:

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

我需要查询上面的输出......

2 个答案:

答案 0 :(得分:0)

您可以使用条件求和来执行此操作

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

答案 1 :(得分:0)

我想这会解决问题:

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