【发布时间】: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]真的是字符串数据类型而不是某种整数吗?