我有两个非常相似的SQL查询,它们返回在不同工作区上花费的分钟数。
是否可以将它们压缩成一个查询?
所需参数:
显示当月(1月的IE 1,4月的4) 将两个查询的总分钟数显示在一个查询中。
以下是我目前的查询:
SELECT SUM(r.Minutes_Spent) AS 'Custom Programming and Consulting'
FROM TK_Project p
INNER JOIN TK_Task t
ON p.Project_ID = t.Project_ID JOIN TK_Time_Record r
ON t.ID = r.Task_ID
WHERE p.Company = 162
AND p.Name ='Technical Support'
AND r.Work_Date BETWEEN '04/01/2001' AND '04/30/2012'
AND r.Type NOT LIKE '%non%'
AND (r.Type = 'Programming-Billable' OR r.Type = 'Consulting-Billable')
SELECT SUM(r.Minutes_Spent) AS 'Tech. Support / Data Maint. / Training'
FROM TK_Project p
INNER JOIN TK_Task t
ON p.Project_ID = t.Project_ID JOIN TK_Time_Record r
ON t.ID = r.Task_ID
WHERE p.Company = 162
AND p.Name ='Technical Support'
AND r.Work_Date BETWEEN '04/01/2001' AND '04/30/2012'
AND r.Type NOT LIKE '%non%'
AND (r.Type = 'Data Maintenance' OR r.Type = 'Tech Support-Billable' OR r.Type = 'Training')
以下是他们提供的数据:
Custom Programming and Consulting
90
Tech. Support / Data Maint. / Training
105
是否可以将上述查询推送到一个查询中并返回以下数据:
Month Custom Programming and Consulting Tech. Support / Data Maint. / Training
4 90 105
月份需要显示查询这一部分的当前月份:
AND r.Work_Date BETWEEN '04/01/2001' AND '04/30/2012'
我不确定实现这一目标的最佳方法。我需要这个月,因为下一部分我需要将其升级为从今天起12个月后才能获得图形条形图报告。
答案 0 :(得分:2)
是的。 。 。您只需要在SELECT子句中使用case语句按照您需要的方式对值进行分组:
SELECT
SUM(case
when r.Type in ('Programming-Billable', 'Consulting-Billable')
then r.Minutes_Spent
end) AS "Custom Programming and Consulting",
SUM(case
when (r.Type in ('Data Maintenance', 'Tech Support-Billable', 'Training')
then r.Minutes_Spent
end) AS "Tech. Support / Data Maint. / Training"
FROM TK_Project p
INNER JOIN TK_Task t
ON p.Project_ID = t.Project_ID
JOIN TK_Time_Record r
ON t.ID = r.Task_ID
WHERE p.Company = 162
AND p.Name ='Technical Support'
AND r.Work_Date BETWEEN '04/01/2001' AND '04/30/2012'
AND r.Type NOT LIKE '%non%'