sql小計匯總 rollup用法執行個體分析

來源:互聯網
上載者:User

這裡介紹sql server2005裡面的一個使用執行個體:
CREATE TABLE tb(province nvarchar(10),city nvarchar(10),score int)
INSERT tb SELECT '陝西','西安',3
UNION ALL SELECT '陝西','安康',4
UNION ALL SELECT '陝西','漢中',2
UNION ALL SELECT '廣東','廣州',5
UNION ALL SELECT '廣東','珠海',2
UNION ALL SELECT '廣東','東莞',3
UNION ALL SELECT '江蘇','南京',6
UNION ALL SELECT '江蘇','蘇州',1
GO
1、 只有一個匯總
select province as 省,sum(score) as 分數 from tb group by province with rollup
結果:
廣東 10
江蘇 7
陝西 9
NULL 26

select case when grouping(province)=1 then '合計' else province end as 省,sum(score) as 分數 from tb group by province with rollup
結果:
廣東 10
江蘇 7
陝西 9
合計 26

2、兩級,中間小計最後匯總
select province as 省,city as 市,sum(score) as 分數 from tb group by province,city with rollup
結果:
廣東 東莞 3
廣東 廣州 5
廣東 珠海 2
廣東 NULL 10
江蘇 南京 6
江蘇 蘇州 1
江蘇 NULL 7
陝西 安康 4
陝西 漢中 2
陝西 西安 3
陝西 NULL 9
NULL NULL 26
select province as 省,city as 市,sum(score) as 分數,grouping(province) as g_p,grouping(city) as g_c from tb group by province,city with rollup

結果:
廣東 東莞 3 0 0
廣東 廣州 5 0 0
廣東 珠海 2 0 0
廣東 NULL 10 0 1
江蘇 南京 6 0 0
江蘇 蘇州 1 0 0
江蘇 NULL 7 0 1
陝西 安康 4 0 0
陝西 漢中 2 0 0
陝西 西安 3 0 0
陝西 NULL 9 0 1
NULL NULL 26 1 1

select case when grouping(province)=1 then '合計' else province end 省,
case when grouping(city)=1 and grouping(province)=0 then '小計' else city end 市,
sum(score) as 分數
from tb group by province,city with rollup
結果:
廣東 東莞 3
廣東 廣州 5
廣東 珠海 2
廣東 小計 10
江蘇 南京 6
江蘇 蘇州 1
江蘇 小計 7
陝西 安康 4
陝西 漢中 2
陝西 西安 3
陝西 小計 9
合計 NULL 26

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.