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

-- 分类查询查询描述

--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 关键字来过滤。

 

 

原文地址:https://www.cnblogs.com/Gaojier/p/2783557.html