学好php,坚持自己的路,我的网店:http://shop34276988.taobao.com(对直销不信任者没必要访问),想了解直销请访问www.wanmei100.cn
group、grouping、rollup、cube的用法和区别
上一篇 /
下一篇 2008-04-17 16:21:39
/ 个人分类:数据库
--创建测试表
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 子句相联系的选择列表中才允许分组。
相关阅读:
- PHP程序访问数据库 (bjbj, 2008-1-23)
- WebLogic Server 10.3增加了HTTP Pub/Sub服务器 (menmenyouyou, 2008-1-29)
- MySQL集群配置 (tiantang_88, 2008-2-17)
- 一个数据库操作类(跨MYSQL,MSSQL,PG) (mjhui, 2008-2-17)
- Firebird数据库概述 (tiantang_88, 2008-2-20)
- mysqldump具体用法 (tiantang_88, 2008-2-26)
- Access,MySQL月影数据库处理通用类(月影1.1版) (danyidanfei, 2008-3-09)
- mysql4升级到mysql5遇到的数据问题 (007sai, 2008-3-14)
- mysql常用命令 (magicybin, 2008-3-19)
- 刚写的数据库备份&&恢复类 (04007147, 2008-4-14)
导入论坛
收藏
分享给好友
管理
举报
TAG:
rollup
grouping
cube
group
数据库