简体   繁体   English

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

[英]CASE Expression returning NULL when with other case statements, returns expected result when alone

When i run this line of code alone i get the expected result of 1: 当我单独运行这一行代码时,我得到了预期的结果1:

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

However when i run with multiple case statements together as shown in this example all case statements return NULL: 但是,当我与多个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

When they should actually be returning their own numbers, and do so when ran alone, is there a case statement behaviour i'm missing here? 当他们实际上应该返回自己的数字,而当他们一个人跑时这样做时,我是否缺少案例陈述行为?

In standard SQL, this should not return any results (other than an error): 在标准SQL中,这不应返回任何结果(错误除外):

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

because aggregation functions cannot be nested. 因为聚合函数不能嵌套。 Oracle does allow nesting them, but I don't commend using that functionality -- a subquery is simple enough. Oracle确实允许嵌套它们,但是我不推荐使用该功能-子查询非常简单。

In any case, I'm pretty sure that you actually intend: 无论如何,我很确定您确实打算:

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

仅使用一个聚合函数而不嵌套的翻译查询的另一种方法是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM