如何用单条MySQL语句统计单列不同值的多项目数量
MySQL行转列:统计员工各结果类型的数量
你遇到的是典型的**行转列(Pivot Table)**需求,我来帮你理清问题和解决方案:
你的原始数据
首先看你提供的员工结果表:
| Employee | Result |
|---|---|
| Employee 1 | yes |
| Employee 2 | no |
| Employee 3 | divided |
| Employee 4 | no answer |
| Employee 4 | yes |
| Employee 1 | no |
| Employee 2 | no answer |
你想要的输出
希望通过单条查询得到按员工分组,统计每种结果出现次数的表格:
| Employee | Yes | No | Divided | No answer |
|---|---|---|---|---|
| Employee 1 | 1 | 1 | 0 | 0 |
| Employee 2 | 0 | 1 | 0 | 1 |
| Employee 3 | 0 | 0 | 1 | 0 |
| Employee 4 | 1 | 0 | 0 | 1 |
你尝试的问题
你提到用了DISTINCT+GROUP BY,还试了这段代码:
select Employee, Count(Result= 'Yes') as Yes, Count(Result= 'No') as No, Count(Result= 'Divided') as Divided, Count(Result= 'No answer') As Noanswer from My.Table group by Employee
但没得到正确结果,这是因为COUNT()的工作逻辑和你想的不一样。
为什么SUM()可行,COUNT()不行?
在MySQL中,当你写Result = 'yes'这种布尔表达式时,它会返回1(条件成立)或0(条件不成立):
SUM()会把这些1和0累加起来,正好就是符合条件的记录数量,完美匹配你的统计需求。- 而
COUNT()是统计非NULL值的数量,不管表达式是真还是假,Result = 'xxx'的结果永远不是NULL,所以COUNT()会把每一行都算进去,导致所有统计列的数值都等于该员工的总记录数,这显然不对。
正确的查询代码
另外注意你原来的代码里把divided拼写成了diveded,要修正这个拼写错误,否则统计不到对应的数据。正确代码如下:
select employee, sum(Result = 'yes') as 'yes', sum(Result = 'no') as 'no', sum(Result = 'divided') as 'divided', sum(Result = 'no answer') as 'no answer' from your_table group by employee;
内容的提问来源于stack exchange,提问作者Jeffrey Lionel van Houdt
相关产品推荐
相关产品推荐

