我创建了一个可旋转当前表的函数,以便可以查看哪些学生喜欢什么运动。我正在使用oracle db。因此,现在,每种运动在旋转后都位于其各自的列中。如果学生喜欢该特定运动,则标记为1。
Year Student Basketball Baseball Golf Soccer
2019 Michael 1 NA 1 NA
2018 Jason NA NA 1 NA
2017 Sarah 1 1 1 NA
2016 Michelle NA NA NA NA
我想获取体育专栏的数量,以查看有多少学生标记了该体育项目。
select
SUM(CASE WHEN Basketball=1 THEN 1 ELSE 0 END) as NBA,
SUM(CASE WHEN Baseball=1 THEN 1 ELSE 0 END) as MLB,
SUM(CASE WHEN Golf=1 THEN 1 ELSE 0 END) as PGA,
SUM(CASE WHEN Soccer=1 THEN 1 ELSE 0 END) as MLS
from students_sports
group by year
order by 1;
我尝试了上面的语法,但是没有运气。我也尝试过以下语法。
select
sum(nvl("Basketball", 0)) as NBA,
sum(nvl("Baseball", 0)) as MLB,
etc....
运行此查询时,我得到的是行的总数,而不是标记为1的行的实际总数。
答案 0 :(得分:2)
第一种语法是错误的。您将Basketball, Baseball, Golf, Soccer
列设为varchar,因为您要将NA保存在非数字字段中。当您在查询CASE WHEN Basketball=1
中进行比较时,您正在进行数值比较。因此,请按照以下方式更改查询,让我们知道它是否有效。
**Query**
`SELECT SUM (CASE WHEN Basketball = '1' THEN 1 ELSE 0 END) AS NBA
,SUM (CASE WHEN Baseball = '1' THEN 1 ELSE 0 END) AS MLB
,SUM (CASE WHEN Golf = '1' THEN 1 ELSE 0 END) AS PGA
,SUM (CASE WHEN Soccer = '1' THEN 1 ELSE 0 END) AS MLS
FROM students_sports
GROUP BY year
ORDER BY 1;`
示例:
https://dbfiddle.uk/?rdbms=oracle_11.2&fiddle=9c6cc6b067cc128b699316cb299769e3
This should give you result as 1 or 0. Let us know how it goes. I am not sure about your SUM what are you doing with it but it does not make sense to me as that sum will worth nothing.