SELECT country, product, sum(profit) FROM sales GROUP BY country, product WITH ROLLUP;
Before applying ROLLUP (left) vs ROLLUP applied (right)
country | product | sum (profit) | country | product | sum (profit) | |
---|---|---|---|---|---|---|
Finland | Computer | 1500 | Finland | Computer | 1500 | |
Finland | Phone | 110 | Finland | Phone | 110 | |
India | Calculator | 150 | Finland | NULL | 1610 | |
India | Computer | 1200 | India | Calculator | 150 | |
USA | Calculator | 125 | India | Computer | 1200 | |
USA | Computer | 4200 | India | NULL | 1350 | |
USA | TV | 250 | USA | Calculator | 125 | |
USA | Computer | 4200 | ||||
USA | TV | 250 | ||||
USA | NULL | 4575 | ||||
NULL | NULL | 7535 |
ROLLUP replaces the aggregated reference value with a NULL value. With COALESCE you can put whatever text you want.
(Can be replaced with IFNULL in MySQL)
SELECT COALESCE(country,"ALL countries") as country,
COALESCE(product,"ALL products") as product,
sum(profit) FROM sales GROUP BY country, product WITH ROLLUP;
country | product | sum (profit) |
---|---|---|
Finland | Computer | 1500 |
Finland | Phone | 110 |
Finland | ALL products | 1610 |
India | Calculator | 150 |
India | Computer | 1200 |
India | ALL products | 1350 |
USA | Calculator | 125 |
USA | Computer | 4200 |
USA | TV | 250 |
USA | ALL products | 4575 |
ALL countries | ALL products | 7535 |
Reference:
As of MySQL 8.0 , you can use the GROUPING function like Oracle . The result is the same as the query with IFNULL.
The GROUPING value returns 1 or 0 at the ROW where the aggregate should be placed (where NULL is indicated).
The IF statement allows you to replace that point with another character.
SELECT IF(GROUPING(country),'ALL countries',country),
IF(GROUPING(product),'ALL products',country), SUM(profit)
FROM sales GROUP BY country, product WITH ROLLUP;
0 comments:
Post a Comment