[SQL]-Oracle分组函数ROULLUP的应用
时间:2021-07-01 10:21:17
帮助过:3人阅读
CLP.ITEMNAME
AS PORVINCE,
CLC.ITEMNAME
AS CITY,
SUM(
CASE WHEN C2.ITEMNAME=
‘标准产品‘ THEN C.BUSINESSSUM
ELSE 0 END)
AS 标准产品,
SUM(
CASE WHEN C2.ITEMNAME=
‘VIP产品‘ THEN C.BUSINESSSUM
ELSE 0 END)
AS VIP产品,
SUM(C.BUSINESSSUM)
AS 总计
FROM BUSINESS_CONTRACT C
LEFT JOIN STORE_INFO S
ON C.STORES = S.SNO
LEFT JOIN CODE_LIBRARY CLP
ON S.PROVINCE = CLP.ITEMNO
AND CLP.CODENO =
‘ProvinceCodeByHand‘
LEFT JOIN CODE_LIBRARY CLC
ON S.CITY = CLC.ITEMNO
AND CLC.CODENO =
‘CityCodeByHand‘
LEFT JOIN business_type T
ON C.BUSINESSTYPE=T.TYPENO
LEFT JOIN CODE_LIBRARY c2
ON T.PROMOTIONTYPE = C2.ITEMNO
AND C2.CODENO =
‘PromotionType‘
WHERE CLP.ITEMNAME=
‘广东省‘OR CLP.ITEMNAME=
‘湖南省‘
GROUP BY CLP.ITEMNAME,CLC.ITEMNAME
查询结果:
在这里需要在最后加一行汇总行,这里可以用到自动汇总函数ROULLUP,与GROUP BY连用,写法如下:
GROUP BY ROLLUP(CLP.ITEMNAME,CLC.ITEMNAME)
结果如下:
会发现,该函数会对广东省及湖南省都有个小总计,最后是全部的总计,如果只需要对全部做一个总计,可以使用grouping_id进行美化,代码如下:
GROUP BY ROLLUP(CLP.ITEMNAME,CLC.ITEMNAME)
HAVING grouping_id(CLP.ITEMNAME,CLC.ITEMNAME)!=1
结果如下:
这里对grouping_id说明:
总计是grouping_id=3
小计grouping_id=1
记录是grouping_id=0
以上
[SQL]-Oracle分组函数ROULLUP的应用
标签: