将多个联接合并为一个选择/案例

时间:2018-07-06 09:51:13

标签: tsql pivot case

我目前正在使用不同的条件查询一个表4次,然后将左联接作为一个更大的查询的一部分来返回所有数据。较大的查询运行不是特别快,我可以肯定我当前的方法效率不高。

我想知道的是,是否有可能使用CASE语句增加4列之一。我目前有4个查询:

SELECT ts.department, 
                         Sum([hours]) AS ChargeableTimeYTD 
                  FROM   bwbfiles.sos.timesummary ts 
                  WHERE  category = 'C' 
                         AND [year] = '2019' 
                  GROUP  BY department


SELECT ts.department, 
                         Sum([hours]) AS ChargeableTimeMTD 
                  FROM   bwbfiles.sos.timesummary ts 
                  WHERE  category = 'C' 
                         AND [year] = '2019' 
                         AND [period] = 4 
                  GROUP  BY department


SELECT ts.department, 
                         Sum([hours]) AS NonChargeableTimeProBono 
                  FROM   bwbfiles.sos.timesummary ts 
                  WHERE  category = 'NC' 
                         AND ( [act_code] = '001N' 
                                OR [act_code] = '00N6' ) 
                         AND [year] = '2019' 
                  GROUP  BY department


SELECT ts.department, 
                         Sum([hours]) AS NonChargeableTimeNonProBono 
                  FROM   bwbfiles.sos.timesummary ts 
                  WHERE  category = 'NC' 
                         AND ( [act_code] <> '001N' 
                               AND [act_code] <> '00N6' ) 
                         AND [year] = '2019' 
                  GROUP  BY department

目标是最终得到5列的查询结果 部门,ChargeableTimeYTD,ChargeableTimeMTD,NonChargeableTimeProBono,NonChargeableTimeNonProBono

或者我可以代替CASE从每个位删除部门,并进行查询以产生3列

部门,小时数,类别(类别为ChargeableTimeYTD / ChargeableTimeMTD等...等),然后将其分为5列。

谢谢!

1 个答案:

答案 0 :(得分:2)

这可能会满足我的要求

SELECT ts.department, 
    Sum(case when category = 'C' then [hours] else 0 end) AS ChargeableTimeYTD,
    Sum(case when category = 'C' and [period] = 4 then [hours] else 0 end) AS ChargeableTimeMTD,
    Sum(case when category = 'NC' and ([act_code] = '001N' or [act_code] = '00N6') then [hours] else 0 end) AS NonChargeableTimeProBono,
    Sum(case when category = 'NC' and ([act_code] <> '001N' or [act_code] <> '00N6') then [hours] else 0 end) AS NonChargeableTimeNonProBono
FROM   bwbfiles.sos.timesummary ts 
where [year] = '2019'
and [category] in ('C','NC')
GROUP  BY department