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

本文详细介绍了SQL中的GROUP BY、ROLLUP及CUBE功能,通过实例演示如何使用这些功能进行数据聚合,并解释了它们之间的区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

--创建测试表
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 子句相联系的选择列表中才允许分组。

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值