1

假设我们有一个诺贝尔奖(年,主题,获奖者)。

我想得到一个返回年份的结果,当年化学奖数列,当年物理奖数列。

你会怎么做?

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

不起作用。

4

2 回答 2

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
于 2013-04-20T15:24:00.393 回答
1

这行不通吗?

select yr, subject, count(*) awards
from nobel
where subject in ('physics', 'chemistry')
group by yr, subject
于 2013-04-20T15:25:10.787 回答