

例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)
暂无评论。