0

我有两个非常相似的 SQL 查询,它们返回在不同工作区域上花费的分钟数。

是否可以将它们压缩为一个查询?

所需参数:

显示当前月份(IE 1 表示 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 个月以获取图形条形图报告。

4

1 回答 1

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%'
于 2012-05-09T16:15:04.910 回答