Monday, 26 August 2019

MySQL uses WITH ROLLUP instead of ROLLUP .

SELECT country, product, sum(profit) FROM sales GROUP BY country, product WITH ROLLUP;
Before applying ROLLUP (left) vs ROLLUP applied (right)
countryproductsum (profit) countryproductsum (profit)
FinlandComputer1500 FinlandComputer1500
FinlandPhone110 FinlandPhone110
IndiaCalculator150 FinlandNULL1610
IndiaComputer1200 IndiaCalculator150
USACalculator125 IndiaComputer1200
USAComputer4200 IndiaNULL1350
USATV250 USACalculator125
    USAComputer4200
    USATV250
    USANULL4575
    NULLNULL7535
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;
countryproductsum (profit)
FinlandComputer1500
FinlandPhone110
FinlandALL products1610
IndiaCalculator150
IndiaComputer1200
IndiaALL products1350
USACalculator125
USAComputer4200
USATV250
USAALL products4575
ALL countriesALL products7535
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