gpt4 book ai didi

php - mysql单个查询对多个值进行计数

转载 作者:行者123 更新时间:2023-11-29 22:53:19 24 4
gpt4 key购买 nike

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

表格

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

我需要查询上述输出...

最佳答案

您可以使用条件求和来做到这一点

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

关于php - mysql单个查询对多个值进行计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28808131/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com