I cant change the brand name for total product

33 Views Asked by At

i cant seem to change the brand name for total product example is Apple to Grand Total for Apple

I am having a problem with my code this is my code

SELECT Month(PurchaseDate) AS 'Month',CASE
WHEN GROUPING(Brand) = 0 THEN Brand 
When GROUPING(MONTH(PurchaseDate)) = 1 THEN 'Grand Total' 
When GROUPING(Brand) = 1 THEN 'Monthly SubTotal' END AS 'Brand', 
SUM(PRICE) AS 'Total Amount' 
FROM [Purchase_Items]
GROUP BY MONTH(PurchaseDate),Brand with CUBE

This is the output: [My output](https://i.stack.imgur.com/K5lJO.png)

But this is what i expected to be output: [Expected output](https://i.stack.imgur.com/LtQwh.png)

Pls help me

1

There are 1 best solutions below

0
Ikhlaq Hussain On

I amended line 3 and changed the statement to THEN 'Grand Total for ' + Brand. I then swapped line 2 and 3

Finally put in a CTE table to replace the Null with 'Grand Total'

The result is exactly what you got.

WITH cte AS (
SELECT Month(PurchaseDate) AS 'Month',
    CASE
        WHEN GROUPING(MONTH(PurchaseDate)) = 1 THEN 'Grand Total for ' + Brand 
        WHEN GROUPING(Brand) = 0 THEN Brand 
        WHEN GROUPING(Brand) = 1 THEN 'Monthly SubTotal'
    END AS 'Brand', 
    SUM(PRICE) AS 'Total Amount' 
FROM #total
GROUP BY MONTH(PurchaseDate),Brand with CUBE)

SELECT [Month],Isnull(Brand,'Grand Total'),[Total Amount]
FROM cte

CTE Brand