group、grouping、rollup、cube的用法和区别(本文来自优快云博客,转载请标明出处:http://blog.youkuaiyun.com/junmail/archive/2006/12/26/1463132.aspx)

本文详细解析了SQL中的GROUP BY、ROLLUP及CUBE功能,通过实例对比了ROLLUP和CUBE的区别,并介绍了GROUPING函数的应用场景。

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

(8)  SELECT (9) DISTINCT (11) <TOP_specification> <select_list>
(1)  FROM <left_table>
(3)    <join_type> JOIN <right_table>
(2)      ON <join_condition>
(4)  WHERE <where_condition>
(5)  GROUP BY <group_by_list>
(6)  WITH {CUBE | ROLLUP}
(7)  HAVING <having_condition>
(10) ORDER BY <order_by_list>


要点:
第一:执行顺序,每个执行从句生成一个查询者不可见的事实表,执行顺序如序号所示。
第二:with{cube|rollup}的应用:
    group、grouping、rollup、cube的用法和区别
--创建测试表
if exists(select name from sysobjects where name=N'test' and type='U')
DROP TABLE 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 运算符添加行时,附加的列输出值为,当所添加的行不是由CUBE 或ROLLUP 产生时,附加列值为。
仅在与包含CUBE 或ROLLUP 运算符的GROUP BY 子句相联系的选择列表中才允许分组。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值