My data looks like this
date | category | subcategory | price |
---|---|---|---|
20230510 | A | LMN | 10 |
20230510 | A | PQR | 20 |
20230511 | A | LMN | 50 |
20230511 | A | PQR | 10 |
In my table I am getting subcategory LMN and PQR along with price, I need to introduce row ALL with the addition of the price for LMN and PQR subcategory using optimized query
My expected output is like this
date | category | subcategory | price |
---|---|---|---|
20230510 | A | LMN | 10 |
20230510 | A | PQR | 20 |
20230510 | A | ALL | 30 |
20230511 | A | LMN | 50 |
20230511 | A | PQR | 10 |
20230511 | A | ALL | 60 |
I tried using UNION ALL to generate a row to ALL and the addition of the price at category level and displaying but is there anyway that I can do this same thing without using UNION ALL or SELF JOIN so reduce table scans
Query I tried –
select date,
category,
'ALL' as subcategory
sum(price)
from table
group by date,category
UNION ALL
select date,
category,
subcategory,
price
from table;
2
Answers
Use the conditional aggregation to get total price of
LMN
andPQR
only :If not interested by filtering your data by subcategory, then :
Demo here
You could use rollup: