如何在MySQL的两种不同情况下统计同一列?

时间:2015-01-24 17:02:45

标签: mysql

假设具有以下架构的演示表课程

courseId    keyId
   2         0
   2         3
   2         4
   3         5
   3         0
   3         0

查询的预期输出应单独计算courseId的数量,其中0和其他单独计算。 实施例

courseId    ZeroCount    NonZeroCount
   2           1             2
   3           2             1

请帮助我,我被困在这个。

1 个答案:

答案 0 :(得分:3)

对于MySQL使用

select courseId, 
       sum(keyId = 0) as ZeroCount, 
       sum(keyId <> 0) as NonZeroCount
from your_table
group by courseId

和ANSI标准SQL

select courseId, 
       sum(case when keyId = 0 then 1 else 0 end) as ZeroCount, 
       sum(case when keyId <> 0 then 1 else 0 end) as NonZeroCount
from your_table
group by courseId