我有一张表,其中包含年份和性别。这是我的桌子的一个例子:
YEAR Sex
1999 M
1999 M
1999 F
1999 F
我使用此查询获取结果。
SELECT YEAR,COUNT(*)
FROM athlete_events
WHERE SEX = 'M'
GROUP BY YEAR;
我在输出中看到此结果:
YEAR COUNT(*)
1999 2
但是我想看到这个结果:
YEAR COUNT_MALE COUNT_FEMALE
1999 2 2
在Pracle SQL中有可能吗?
答案 0 :(得分:7)
您可以使用case表达式进行条件聚合:
select year,
count(case when sex = 'M' then year end) as count_male,
count(case when sex = 'F' then year end) as count_female
from athlete_events
group by year;
YEAR COUNT_MALE COUNT_FEMALE
---------- ---------- ------------
1999 2 2
count函数将忽略空值,因此不计算与指定标志不匹配的行(在case表达式中默认为null;如果愿意,可以使用显式else null
)。
(我个人更喜欢使用count()
而不是sum()
,因为这样可以更好地反映您的实际工作-计算事情。)
答案 1 :(得分:6)
您需要条件聚合:
select year,
sum(case when SEX = 'M' then 1 else 0 end) as count_male,
sum(case when SEX = 'F' then 1 else 0 end) as count_female
from athlete_events
group by year;
答案 2 :(得分:4)
您可以执行子查询,如下所示:
SELECT
E.YEAR,
(select count(*) from athlete_events M where M.YEAR=E.YEAR and M.SEX='M') COUNT_MALE,
(select count(*) from athlete_events F where F.YEAR=E.YEAR and F.SEX='F') COUNT_FEMALE
FROM athlete_events E
GROUP BY E.YEAR;
这比条件聚合要昂贵(在性能方面),另一方面,它可能更易于理解和维护。