Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to set the first column value of a GROUPING SETS

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:

enter image description here


Related:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading