ROLLUP,Cube, grouping sets

ROLLUP

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

表示给定的表达式列表及其所有前缀(包括空列表),等效于:

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;

表示给定表达式列表的所有组合,等效于:

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),());

表示给定表达式列表的分组,等效于:

Group by (a,b) union all

Group by (b,c) union all

Group by ();

功能介绍

设计一个表,表格式如下:

ROLLUP,Cube, grouping sets_第1张图片

向表中插入下列数据

ROLLUP,Cube, grouping sets_第2张图片

我们可以使用下面的语句分组查询总收益:

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

当我们想知道某一层次的小计时,比如某年某国所有产品的收益,可以使用ROLL UP

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

ROLLUP,Cube, grouping sets_第3张图片

但ROLL UP只展示所选列某个层次,当我们想知道所选列全部组合时,就可以使用CUBE

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

ROLLUP,Cube, grouping sets_第4张图片

我们有时也需要自己选择想要查询的列,此时可以使用grouping sets

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

 ROLLUP,Cube, grouping sets_第5张图片

你可能感兴趣的:(sql,数据库)