Search code examples
sqlsql-servert-sqlsql-server-2012sql-server-2016

Combine three (3) queries into one


I would like to combine these three queries into one query:

SELECT County, Result1, COUNT(Result1) AS Result1Total
FROM MainData
WHERE (((Date) BETWEEN '01/01/2020' AND '01/30/2020'))
GROUP BY County, Result1
ORDER BY County;

SELECT County, Result2, COUNT(Result2) AS Result2Total
FROM MainData
WHERE (((Date) BETWEEN '01/01/2020' AND '01/30/2020'))
  AND Result2 <> 'NULL'
GROUP BY County, Result2
ORDER BY County;

SELECT County, Result3, COUNT(Result3) AS Result3Total
FROM MainData
WHERE (((Date) BETWEEN '01/01/2020' AND '01/30/2020'))
  AND Result3 <> 'NULL'
GROUP BY County, Result3
ORDER BY County;

I would like the output to look as follows:

County        Result         Totals
-----------------------------------    
Allegany      Car Services     2
Richmond      Car Services     3
Lynchberg     House Services   5
Charlotte     Car Services     12
Charlotte     House Services   2
NorthHampton  Car Serivces     6
NorthHampton  House Services   8

Results 1, 2 and 3 are dropdown boxes with the same information.


Solution

  • Looks like GROUPING SETS would come in handy here:

    SELECT
        County,
        ISNULL(ISNULL(Result1, Result2), Result3) AS Result,
        COUNT(Result1) AS Result1Total
    FROM MainData
    WHERE (((Date) BETWEEN '01/01/2020' AND '01/30/2020'))
    GROUP BY GROUPING SETS (
        (County, Result1),
        (County, Result2),
        (County, Result3)
    )
    ORDER BY County;
    

    If the Result columns are nullable then you need a more complex expression:

        CASE WHEN GROUPING(Result1) = 0 THEN Result1
             WHEN GROUPING(Result1) = 0 THEN Result2
             ELSE Result3
        END AS Result,