与其他case语句一起使用时,CASE表达式返回NULL,在单独时返回预期结果

时间:2019-06-04 11:33:06

标签: sql oracle oracle-sqldeveloper

当我单独运行这一行代码时,我得到了预期的结果1:

sum(case when facilityname like '%AT%' then count(status) else 0 end) as AT_all_status

但是,当我同时运行多个case语句时(如本示例所示),所有case语句都返回NULL:

sum(case when facilityname like '%AT%' then count(status) else 0 end) as AT_all_status,
sum(case when facilityname like '%AT%' and status in ('Current','Approved') then count(status) else 0 end) as AT_approved_current,
sum(case when facilityname like '%CZ%' then count(status) else 0 end) as CZ_all_status,
sum(case when facilityname like '%CZ%' and status in ('Current','Approved') then count(status) else 0 end) as CZ_approved_current,
sum(case when facilityname like '%FGE%' then count(status) else 0 end) as FGE_all_status,
sum(case when facilityname like '%FGE%' and status in ('Current','Approved') then count(status) else 0 end) as FGE_approved_current,
sum(case when facilityname like '%FRA%' then count(status) else 0 end) as FRA_all_status,
sum(case when facilityname like '%FRA%' and status in ('Current','Approved') then count(status) else 0 end) as FRA_approved_current

当他们实际上应该返回自己的数字时,而当他们一个人跑时这样做时,我是否缺少案例陈述行为?

2 个答案:

答案 0 :(得分:2)

在标准SQL中,这不应返回任何结果(错误除外):

sum(case when facilityname like '%AT%' then count(status) else 0 end) as AT_all_status

因为聚合函数不能嵌套。 Oracle确实允许嵌套它们,但是我不推荐使用该功能-子查询非常简单。

无论如何,我很确定您的实际意图:

sum(case when facilityname like '%AT%' then 1 else 0 end) as AT_all_status

答案 1 :(得分:1)

另一种仅使用一个聚合函数而不嵌套的查询方式如下:

count(case when facilityname like '%AT%' then status end)