SQL 301 – GROUPING

 

In our previous lesson we covered WITH ROLLUP  and WITH CUBE.  During that lesson you may have noticed that when we saw the summary rows, the columns had NULL as the value.  Hopefully you wondered to yourself, how do I know programatically which of the rows are summary lines and which are rows that just had NULL for the value of that column?

Well that’s where GROUPING() comes in.  With GROUPING(), you get a 1 where the row is a summary row, and 0 if it isn’t.

Let’s look at our previous WITH CUBE query.

SELECT Type, Store, SUM(Number) as Number
FROM items
GROUP BY type,store
WITH CUBE

We got the results:

Type Store Number
ShieldTatooine18
ShieldKorriban9
ShieldNULL27
BlasterTatooine12
BlasterKorriban5
BlasterDantooine14
BlasterNULL31
Lightsaber CrystalKorriban1
Lightsaber CrystalDantooine4
Lightsaber CrystalNULL5
NULLNULL63
NULLTatooine30
NULLKorriban15
NULLDantooine18

In this case all of those NULLs are summary lines, so if we changed the query to:

SELECT
    CASE WHEN Type IS NOT NULL THEN Type ELSE
      CASE WHEN GROUPING(Type) = 1 THEN
        CASE WHEN GROUPING(store) = 0 'Subtotal Type' ELSE 'Grand Total' END
      ELSE
        'N/A'
      END
    END as Type
  , CASE WHEN Store IS NOT NULL THEN Type ELSE
      CASE WHEN GROUPING(Store) = 1 THEN
        CASE WHEN GROUPING(Type) = 0 'Subtotal Store' ELSE 'Grand Total' END
      ELSE
        'N/A'
      END
    END as Store
  , SUM(Number) as Number
FROM items
GROUP BY type,store
WITH CUBE

We’d get a bit nicer output.

Type Store Number
ShieldTatooine18
ShieldKorriban9
ShieldSubtotal Store27
BlasterTatooine12
BlasterKorriban5
BlasterDantooine14
BlasterSubtotal Store31
Lightsaber CrystalKorriban1
Lightsaber CrystalDantooine4
Lightsaber CrystalSubtotal Store5
Grand TotalGrand Total63
Subtotal TypeTatooine30
Subtotal TypeKorriban15
Subtotal TypeDantooine18

Or, at the very least we’d have a result that tells us exactly what we’re looking at on each row.

Have any questions?  Let me know!  I’m here to help.

 

Tags:

No comments yet.

Leave a Reply

Notify me of followup comments via e-mail. You can also subscribe without commenting.