You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用单条MySQL语句统计单列不同值的多项目数量

MySQL行转列:统计员工各结果类型的数量

你遇到的是典型的**行转列(Pivot Table)**需求,我来帮你理清问题和解决方案:

你的原始数据

首先看你提供的员工结果表:

EmployeeResult
Employee 1yes
Employee 2no
Employee 3divided
Employee 4no answer
Employee 4yes
Employee 1no
Employee 2no answer

你想要的输出

希望通过单条查询得到按员工分组,统计每种结果出现次数的表格:

EmployeeYesNoDividedNo answer
Employee 11100
Employee 20101
Employee 30010
Employee 41001

你尝试的问题

你提到用了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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 20:57:37