Merge two SELECT queries with different WHERE clauses

Treat your two current queries' resultsets as tables and join them:

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.Region

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 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.


Building off Michael's suggestion:

SELECT
    U_REGN AS 'Region',
    SUM(CASE WHEN [status] = -3 THEN 1 ELSE 0 END) AS 'OpenServices',
    SUM(CASE WHEN [status] = -3 AND [description] LIKE '%DFC%' THEN 1 ELSE 0 END) AS 'DFC',
    SUM(CASE WHEN DATEDIFF(day, closeDate, GETDATE()) = 1 THEN 1 ELSE 0 END) AS 'ClosedYesterday'
FROM
    OSCL
GROUP BY 
    U_REGN
ORDER BY
    'OpenServices' desc

Tags:

Sql Server