I have the following request :
SELECT column1, column2, SUM(column3) as total
FROM my_table
GROUP BY GROUPING SETS ((column1, column2), ())
Which returns :
Name1 | Name2 | QTT |
---|---|---|
AB | CD | 15 |
ZE | EF | 15 |
None | None | 30 |
So |None|None|30
is the output from the GROUPING BY SETS
But I am wondering how to define the first None to be something else :
|SubTotal|None|30
For example.
The final output would be :
Name1 | Name2 | QTT |
---|---|---|
AB | CD | 15 |
ZE | EF | 15 |
SubTotal | None | 30 |
>Solution :
The dialect is not provided, but the corresponding part to GROUPING SETS
is GROUPING function:
Describes which of a list of expressions are grouped in a row produced by a GROUP BY query.
GROUPING_ID
is not an aggregate function, but rather a utility function that can be used alongside aggregation, to determine the level of aggregation a row was generated for
CREATE TABLE my_table(Name1 TEXT, Name2 TEXT, QTT INT)
AS SELECT 'AB','CD',15
UNION SELECT 'ZE','EF',15;
SELECT CASE WHEN GROUPING_ID(Name1,Name2)=3THEN 'Subtotal' ELSE Name1 END AS Name1
,Name2, SUM(QTT) as total
FROM my_table
GROUP BY GROUPING SETS ((Name1, Name2), ());
Output:
Related: