【问题标题】:Check multiple case expressions result at once一次检查多个 case 表达式结果
【发布时间】:2020-08-05 06:11:24
【问题描述】:

我在 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

现在,我如何检查是否所有案例都返回 0.0?这样我就可以在结果集中排除它?

【问题讨论】:

  • 它可能“看起来”像这样,但它也必须非常不同,因为您提供的内容有语法错误,甚至无法编译。而且您可能只是复制了上一个问题中提供给您的代码。只是没有尝试!

标签: sql sql-server database group-by sql-server-2012


【解决方案1】:

我只想添加一个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

【讨论】:

    【解决方案2】:

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

    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 表达式,而不是case 语句。后者是流控结构,前者是条件逻辑。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-01
      • 2020-08-06
      • 2021-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-07
      相关资源
      最近更新 更多