Sql 一次检查多个大小写表达式结果
我在select语句中的聚合函数中有一个case表达式,看起来像这样Sql 一次检查多个大小写表达式结果,sql,sql-server,database,group-by,sql-server-2012,Sql,Sql Server,Database,Group By,Sql Server 2012,我在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
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?因此,我可以在结果集中排除它?最简单的方法可能是将查询转换为子查询,然后在外部查询中进行筛选:
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
请注意,您的原始查询缺少一个GROUPBY
子句,我添加了该子句
另一种方法是使用冗长的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
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;
旁注:这称为
case
表达式,而不是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 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
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
它可能“看起来”像这样,但也必须非常不同,因为您提供的内容有语法错误,甚至无法编译。你可以复制上一个问题中给出的代码。只是不尝试!