patternsqlModerate
Merge two SELECT queries with different WHERE clauses
Viewed 0 times
querieswithmergewheredifferenttwoselectclauses
Problem
I have one table of services. I need to merge two SELECT queries. Both have different where clauses. For example
This gives me result
I have another query
It gives me result
I need to merge both results, and show ClosedServices beside the DFC column.
SELECT
U_REGN as 'Region',
COUNT(callID) as 'OpenServices',
SUM(CASE WHEN descrption LIKE '%DFC%' THEN 1 ELSE 0 END) 'DFC'
FROM OSCL
WHERE
([status] = - 3)
GROUP BY
U_REGN
ORDER BY
'OpenServices' descThis gives me result
Region | OpenServices | DFC
Karaci | 14 | 4
Lahore | 13 | 3
Islamabad | 10 | 4I have another query
SELECT
U_REGN as 'Region',
COUNT(callID) as 'ClosedYesterday'
FROM OSCL
WHERE
DATEDIFF(day, closeDate, GETDATE()) = 1
GROUP BY
U_REGN
ORDER BY
'ClosedYesterday' descIt gives me result
Region | ClosedServices
Karachi | 8
Lahore | 7
Islamabad | 4I need to merge both results, and show ClosedServices beside the DFC column.
Solution
Treat your two current queries' resultsets as tables and join them:
Not the prettiest bit of SQL I've ever written but hopefully you'll see how it works and understand how to maintain it.
I suspect a better-performing query would be a single
select
FirstSet.Region,
FirstSet.OpenServices,
FirstSet.DFC,
SecondSet.ClosedYesterday
from
(
SELECT U_REGN as 'Region', COUNT(callID) as 'OpenServices',
SUM(CASE WHEN descrption LIKE '%DFC%' THEN 1 ELSE 0 END) 'DFC'
FROM OSCL
WHERE ([status] = - 3)
GROUP BY U_REGN
--ORDER BY 'OpenServices' desc
) as FirstSet
inner join
(
SELECT U_REGN as 'Region',
COUNT(callID) as 'ClosedYesterday'
FROM OSCL
WHERE DATEDIFF(day, closeDate, GETDATE()) = 1
GROUP BY U_REGN
--ORDER BY 'ClosedYesterday' desc
) as SecondSet
on FirstSet.Region = SecondSet.Region
order by FirstSet.RegionNot the prettiest bit of SQL I've ever written but hopefully you'll see how it works and understand how to maintain it.
I suspect a better-performing query would be a single
SELECT from OSCL, grouped by U_REGN, with each of your three counters as separate SUM(CASE ...) statements akin to what you do currently for DFC. This will be a single table scan, at most, depending you your indexes & schema.Code Snippets
select
FirstSet.Region,
FirstSet.OpenServices,
FirstSet.DFC,
SecondSet.ClosedYesterday
from
(
SELECT U_REGN as 'Region', COUNT(callID) as 'OpenServices',
SUM(CASE WHEN descrption LIKE '%DFC%' THEN 1 ELSE 0 END) 'DFC'
FROM OSCL
WHERE ([status] = - 3)
GROUP BY U_REGN
--ORDER BY 'OpenServices' desc
) as FirstSet
inner join
(
SELECT U_REGN as 'Region',
COUNT(callID) as 'ClosedYesterday'
FROM OSCL
WHERE DATEDIFF(day, closeDate, GETDATE()) = 1
GROUP BY U_REGN
--ORDER BY 'ClosedYesterday' desc
) as SecondSet
on FirstSet.Region = SecondSet.Region
order by FirstSet.RegionContext
StackExchange Database Administrators Q#63506, answer score: 17
Revisions (0)
No revisions yet.