木子屋 Dnawo's BLOG

SQL Server2000:ROLLUP和CUBE运算符使用

👤 dnawo 📅 2010-04-16 👁 5624 👍 0 💬 0 🔄 本站原创
ROLLUP、CUBE运算符和GROUP BY一起使用能在结果集中加入一些额外的统计信息,例如有一张OrderDetail表,结构和数据如下:

图片

图片

例1:统计每个订单的产品数量。

select orderid,sum(quantity) as quantity from orderDetail 
group by orderid
with rollup

结果集:
图片

如图所示,ROLLUP统计出了所有订单的产品数。

例2:统计每个订单、每种产品的数量。

select orderid,productid,sum(quantity) as quantity from orderDetail 
group by orderid,productid
with rollup

结果集:
图片

如图所示,ROLLUP统计出了每笔订单的产品数以及所有订单的产品数。

例3:统计每个订单、每种产品的金额。

select orderid,productid,quantity,sum(price*quantity) as total from orderDetail 
group by orderid,productid,quantity
with rollup

结果集:
图片

如图所示,ROLLUP统计出了每笔订单的金额以及所有订单的金额。

例4:当GROUP BY后边有多个字段时,字段的前后顺序不同,结果就会不同,用例2做测试。

select orderid,productid,sum(quantity) as quantity from orderDetail 
group by productid,orderid
with rollup

结果集:
图片

小结

·ROLLUP得紧跟在GROUP BY后边使用;
·GROUP BY后边字段的前后顺序影响ROLLUP的结果;
·ROLLUP将GROUP BY后边字段从右到左依次为NULL再汇总其他聚合列的值;

例5:再以例2为例,CUBE运算符结果为例2和例4结果集的并集。

select orderid,productid,sum(quantity) as quantity from orderDetail 
group by orderid,productid
with cube

结果集:
图片

小结

·和ROLLUP运算符不同的是CUBE运算符不受GROUP BY后边字段的前后顺序的影响,CUBE运算符将GROUP BY后边字段排列组合设置为NULL再汇总其他聚合列的值;

GROUPING函数

GROUPING函数可以判断列的值是否是ROLLUP、CUBE运算符生成的,若则则函数值为1,否则为0。再来看一个例子:

select orderid,grouping(orderid) as g1,productid,grouping(productid) as g2,sum(quantity) as quantity from orderDetail 
group by orderid,productid
with rollup

结果集:
图片

评论(0)

暂无评论。

计算题
评论需审核通过后显示
← 上一篇 使用SQL Server2000关系图管理表 下一篇 → SQL Server2000:COMPUTE函数