【问题标题】:Merging several joins into a single select / case将多个联接合并到一个选择/案例中
【发布时间】:2018-12-14 21:37:39
【问题描述】:

我目前正在使用不同的条件查询一个表 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 列的查询

Department、Hours、Category(其中 Category 是 ChargeableTimeYTD/ChargeableTimeMTD 等...等等),然后将其转为 5 列。

提前致谢!

【问题讨论】:

  • [year] 真的是字符串数据类型而不是某种整数吗?

标签: tsql pivot case


【解决方案1】:

这可能会满足您的要求

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

【讨论】:

  • 使用... where [year] = '2019' ...可以提高性能,简化逻辑。它还可以过滤category in ( 'C', 'NC' ) 以减少处理的行数。
  • [act_code] &lt;&gt; '001N' or [act_code] &lt;&gt; '00N6' 在原始查询中是 and,而不是 or
  • 非常感谢你——当你看到它的时候感觉很有意义,所以不确定我为什么会想到枢轴。有很多领域我可以使用这种技术,所以再次非常感谢你。编。
猜你喜欢
  • 2014-09-09
  • 1970-01-01
  • 1970-01-01
  • 2019-03-23
  • 1970-01-01
  • 2015-02-02
  • 2020-04-04
  • 2012-12-07
  • 1970-01-01
相关资源
最近更新 更多