计算SQL中值的出现次数

时间:2013-04-20 15:22:38

标签: sql count group-by

让我们说我们有诺贝尔奖(年,主题,获胜者)。

我希望得到的结果将是当年的化学奖项数量列,当年的物理奖项数量列。

你会怎么做?

SELECT yr, count(subject='Physics'), count(subject='Chemistry') FROM nobel GROUP BY yr 

不起作用。

2 个答案:

答案 0 :(得分:4)

您的查询不起作用,因为条件返回值0或1,count计算非NULL值。

尝试使用sum代替count

SELECT yr, sum(subject='Physics'), sum(subject='Chemistry')
FROM nobel
GROUP BY yr

顺便说一下,并非所有数据库都将条件表达式视为整数。标准语法是:

select yr, sum(case when subject = 'Physics' then 1 else 0 end) as NumPhysics,
       sum(case when subject = 'Chemistry' then 1 else 0 end) as NumChemistry
from nobel
group by yr

您还可以通过执行以下操作获取有关多行的相同信息:

select yr, subject, count(*)
from Nobel
where subject in ('Physics', 'Chemistry')
group by yr, subject

答案 1 :(得分:1)

这不会起作用吗?

select yr, subject, count(*) awards
from nobel
where subject in ('physics', 'chemistry')
group by yr, subject