group、grouping、rollup、cube的用法和区别

来源:互联网 发布:it人才 编辑:程序博客网 时间:2024/06/05 10:04

use test
create table test(id int,sort char(10),color char(10),num int constraint pk_test primary key(id,sort,color))
--插入数据
insert into test
select 1,'book','blue',10
union all
select 1,'book','green',10
union all
select 1,'book','red',10
union all
select 1,'car','blue',10
union all
select 1,'car','red',10
union all
select 2,'car','red',10
--group by
select sort,color,sum(num) as num from test group by sort,color
--输出结果
--book          blue          10
--car           blue          10
--book          green         10
--book          red           10
--car           red           20
--group by with rollup
select
case
when grouping(sort)=1 then 'all'
else isnull(sort,'unknow')
end as sort,
case
when grouping(color)=1 then 'all'
else isnull(color,'unknow')
end as color,
sum(num) as num from test
group by sort,color with rollup
--输出结果
--book          blue          10
--book          green         10
--book          red           10
--book          all           30
--car           blue          10
--car           red           20
--car           all           30
--all           all           60
--group by with cube
select
case
when grouping(sort)=1 then 'all'
else isnull(sort,'unknow')
end as sort,
case
when grouping(color)=1 then 'all'
else isnull(color,'unknow')
end as color,
sum(num) as num from test
group by sort,color with cube
--输出结果
--book          blue          10
--book          green         10
--book          red           10
--book          all           30
--car           blue          10
--car           red           20
--car           all           30
--all           all           60
--all           blue          20
--all           green         10
--all           red           30
总结:
1、CUBE 和 ROLLUP区别:
?    CUBE 生成的结果集显示了所选列中值的所有组合的聚合。
?    ROLLUP 生成的结果集显示了所选列中值的某一层次结构的聚合。
2、GROUPING是一个聚合函数,它产生一个附加的列,当用 CUBE 或 ROLLUP 运算符添加行时,附加的列输出值为1,当所添加的行不是由 CUBE 或 ROLLUP 产生时,附加列值为0。
仅在与包含 CUBE 或 ROLLUP 运算符的 GROUP BY 子句相联系的选择列表中才允许分组。