一次检查多个 case 表达式结果

Check multiple case expressions result at once

我在 select 语句中的聚合函数内有一个 case 表达式,看起来像这样。

select person_id,
    sum(case status = 'approved' then hours else 0.0 end) as hours
    sum(case status = 'cancelled' then void_hrs else 0.0 end) as void_hrs
    sum(case status = 'forwarded' then fwd_hrs else 0.0 end) as fwd_hrs
from table

现在,我如何检查所有情况 returns 是否为 0.0?以便我可以在结果集中排除它?

最简单的方法可能是将查询转换为子查询,然后在外部查询中进行过滤:

select *
from (
    select person_id,
        sum(case status = 'approved' then hours else 0.0 end) as hours
        sum(case status = 'cancelled' then void_hrs else 0.0 end) as void_hrs
        sum(case status = 'forwarded' then fwd_hrs else 0.0 end) as fwd_hrs
    from mytable
    group by person_id
) t
where hours + void_hrs + fwd_hrs > 0

请注意,您的原始查询缺少 group by 子句,这是我添加的。

另一种方法是使用冗长的 having 子句:

select person_id,
    sum(case status = 'approved' then hours else 0.0 end) as hours
    sum(case status = 'cancelled' then void_hrs else 0.0 end) as void_hrs
    sum(case status = 'forwarded' then fwd_hrs else 0.0 end) as fwd_hrs
from mytable
group by person_id
having sum(
    case status 
        when 'approved' then hours
        when 'cancelled' then void_hrs
        when 'forwarded' then fwd_hrs
        else 0.0
    end
) > 0

旁注:这称为 case 表达式 ,而不是大小写 语句 。后者是流控结构,前者是条件逻辑。

我只想添加一个 where 子句:

select person_id,
       sum(case status = 'approved' then hours else 0.0 end) as hours
       sum(case status = 'cancelled' then void_hrs else 0.0 end) as void_hrs
       sum(case status = 'forwarded' then fwd_hrs else 0.0 end) as fwd_hrs
from table
where status in ('approved', 'cancelled', 'forwarded')
group by person_id;

作为奖励,如果您有很多具有其他状态的行,这可能会提高性能。

或者,您可以在查询中添加 having 子句:

having sum(case when status in ('approved', 'cancelled', 'forwarded') then 1 else 0 end) > 0