ROLLUP,Cube, grouping sets

ROLLUP

Group by (a,b,c) with rollup;

represents the given list of expressions and all their prefixes (including the empty list), equivalent to:

Group by (a,b,c) union all

Group by (a,b) union all

Group by (a) union all

Group by ();

CUBE

Group by (a,b,c) with cube;

represents all combinations of the given expression list, equivalent to:

Group by (a,b,c) union all

Group by (a,b) union all

Group by (a,c) union all

Group by (b,c) union all

Group by (a) union all

Group by (b) union all

Group by (c) union all

Group by ();

GROUPING SETS

Group by grouping sets((a,b),(b,c),());

represents a grouping of the given list of expressions, equivalent to:

Group by (a,b) union all

Group by (b,c) union all

Group by ();

Features

Design a table with the following format:

Insert the following data into the table

We can use the following statement to group and query the total revenue:

select year,country,product,sum(profit) 
    from sales 
        group by year,country,product;

When we want to know the sub-level of a certain level, such as the income of all products in a certain country in a certain year, we can use ROLL UP

select year,country,product,sum(profit) 
    from sales 
        group by year,country,product with rollup;

But ROLL UP only shows a certain level of the selected column. When we want to know all the combinations of the selected columns, we can use CUBE

select year,country,product,sum(profit) 
    from sales 
        group by year,country,product with cube;

Sometimes we also need to choose the columns we want to query by ourselves. At this time, we can use grouping sets

select year,country, product,sum(profit) 
    from sales 
        group by grouping sets ((year,country),(year,product),());

 

Guess you like

Origin blog.csdn.net/xuejianxinokok/article/details/131090526