将不同的条件选择查询合并为一个 - 具有结构

时间:2016-03-21 17:55:16

标签: sql sql-server sql-server-2008

我在SQL Server 2008中有一个查询,如下所示:

;with PassiveCases
AS
(  
  Select t1.id, COUNT(*) as PassiveCounts
  from #Table1 t1
  inner join Table2 t2 on t2.Id = t1.SurgicalRequest_Id 
  inner join Table3 t3 on t3.Id = t2.ReportingIndicator_Id
  inner join Table3 t4 on t4.Id = t3.Id 
  where t4.Passive = 1              
),
ActiveCases
AS
(
  Select t1.id, COUNT(*) as ActiveCounts
  from #Table1 t1
  inner join Table2 t2 on t2.Id = t1.SurgicalRequest_Id 
  inner join Table3 t3 on t3.Id = t2.ReportingIndicator_Id
  inner join Table3 t4 on t4.Id = t3.Id 
  where t4.Passive = 0  
)

我希望它将这些结构合二为一,以提高效率并提供更多可读性。我正在寻找下面的东西(它不起作用)

:With Cases
AS
(
  Select t1.id, case when t4.Passive = 1 then COUNT(*) as PassiveCounts else COUNT(*) as ActiveCounts
  from #Table1 t1
  inner join Table2 t2 on t2.Id = t1.SurgicalRequest_Id 
  inner join Table3 t3 on t3.Id = t2.ReportingIndicator_Id
  inner join Table3 t4 on t4.Id = t3.Id 
)

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:2)

使用条件聚合。

Select t1.id 
,sum(case when t4.Passive = 1 then 1 else 0 end) as PassiveCounts 
,sum(case when t4.Passive <> 1 then 1 else 0 end) as ActiveCounts
from #Table1 t1
inner join Table2 t2 on t2.Id = t1.SurgicalRequest_Id 
inner join Table3 t3 on t3.Id = t2.ReportingIndicator_Id
inner join Table3 t4 on t4.Id = t3.Id 
group by t1.id

答案 1 :(得分:2)

您只想要条件聚合。但是,在您的情况下,您可以使用算术执行此操作:

for()

根据你的问题,With Cases AS ( Select t1.id, sum(t4.Passive) as PassiveCount, sum(1 - t4.Passive) as ActiveCount from #Table1 t1 inner join Table2 t2 on t2.Id = t1.SurgicalRequest_Id inner join Table3 t3 on t3.Id = t2.ReportingIndicator_Id inner join Table3 t4 on t4.Id = t3.Id group by t1.id ) 只有两个值,所以算术应该做你想要的。