有关rollup和cube的使用方法讨论

本文详细介绍了SQL中的分组函数,包括rollup、cube、grouping及compute等操作符和子句的使用方法,并提供了具体实例。通过这些工具,用户可以更灵活地处理和展示分组数据。

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

<!-- [if gte mso 10]> <mce:style><!-- /* Style Definitions */ table.MsoNormalTable {mso-style-name:普通表格; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-qformat:yes; mso-style-parent:""; mso-padding-alt:0cm 5.4pt 0cm 5.4pt; mso-para-margin:0cm; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:10.5pt; mso-bidi-font-size:11.0pt; font-family:"Calibri","sans-serif"; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-fareast-font-family:宋体; mso-fareast-theme-font:minor-fareast; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin; mso-bidi-font-family:"Times New Roman"; mso-bidi-theme-font:minor-bidi; mso-font-kerning:1.0pt;} -->

<!-- [endif]-->

-- 分类查询查询描述

--rollup 操作符:选列中值的某一层次结构的聚合,返回单个结果集

--cube 操作符:所选列中所有组合的聚合,返回单个结果集

--grouping 操作符:判断结果集中的值是本来就有的,还是使用了 rollup cube 以后产生的

--compute 子句:不支持 text ntext image 数据类型,子句里的字段要和 select 中的字段相同,为字段创建详细的

-- 记录和汇总值,返回多个结果集

--compute by 子句:需要和 order by 一起使用,字段需要是 order by 的子集或全集,创建细节记录和多个汇总值,返回多个结果集

--rollup 的使用方法

select productid, orderID, sum ( quantity) as total from [order details]

group by productid, orderID

with rollup

--cube 的使用方法

select productid, orderID, sum ( quantity) as total from [order details]

group by productid, orderID

with cube

--grouping 的使用方法

select productid, grouping ( productid), orderID, grouping ( orderID), sum ( quantity) as total from [order details]

group by productid, orderID

with cube

select case when ( grouping ( od. productid)= 1) then ' 订单合计: '

else isnull ( od. productid, ' 未知 ' ) end as productID,

case when ( grouping ( od. orderID)= 1) then ' 产品合计: '

else isnull ( od. orderID, ' 未知 ' ) end as productID,

sum ( od. quantity) from ( select convert ( varchar ( 10), productid) as productID, convert ( varchar ( 10), orderID) as orderid, quantity from [order details]) as od

group by productid, orderID

with cube

--compute 的使用方法

select productid, quantity from [order details]

order by productid

compute sum ( quantity) by productid

-- 以上实例可在 SQL Server2000 自带数据库 NorthWind 中可直接运行!

-- 对于使用 cube rollup 引起的合计较多的问题,可以使用 having 关键字和 grouping 关键字来过滤。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值