Reputation: 5150
I have two very similar SQL queries that return a count of minutes spent on a different work area.
Is it possible to condense them into one query?
Parameters needed:
Show the current month (IE 1 for Jan, 4 for April) Show the total minutes count from both queries into one single query.
Here are the queries I have at the moment:
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')
Here is the data they provide:
Custom Programming and Consulting
90
Tech. Support / Data Maint. / Training
105
Is it possible to get the above queries pushed into one query and it return the following data:
Month Custom Programming and Consulting Tech. Support / Data Maint. / Training
4 90 105
The month would need to show the current month that is in this part of the query:
AND r.Work_Date BETWEEN '04/01/2001' AND '04/30/2012'
I'm not sure the best way to achieve this. I need the month because the next part I will need to upgrade this to is to go back 12 months from todays date for a graphical bar chart report.
Upvotes: 0
Views: 484
Reputation: 1270653
Yes . . . you simply need case statements in the SELECT clause to group the values the way you need them:
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%'
Upvotes: 2