您的位置:首页 > 其它

【练手】cube和grouping的分组统计

2010-03-05 17:57 267 查看
------------------------------------------------------------------------
-- author:jc_liumangtu(【DBA】小七)
-- date: 2010-03-05 17:00:41
-- version:
-- Microsoft SQL Server 2005 - 9.00.1399.06 (Intel X86)
--  Oct 14 2005 00:33:37
--  Copyright (c) 1988-2005 Microsoft Corporation
--  Developer Edition on Windows NT 5.1 (Build 2600: Service Pack 3)
--
------------------------------------------------------------------------

use test
set nocount on
if object_id('test2','U') is not null
drop table test2
go
create table test2
(
area char(10),
[month] char(10),
total_sale int
)

insert into test2
select '广州','1月',2000 union all
select '广州','2月',2500 union all
select '深圳','1月',1000 union all
select '深圳','2月',2000
go
select * from test2

select (case when grouping(area)=1 and grouping([month])=1 then '所有地区'
when grouping(area)=1 and grouping([month])=0  then '月份小记' else area end) area
,isnull([month],'总计') [month],sum(total_sale) as [sum(total_sale)]  from test2 group by area,[month]   with cube

area       month      total_sale
---------- ---------- -----------
广州         1月         2000
广州         2月         2500
深圳         1月         1000
深圳         2月         2000

area       month      sum(total_sale)
---------- ---------- ---------------
广州         1月         2000
广州         2月         2500
广州         总计         4500
深圳         1月         1000
深圳         2月         2000
深圳         总计         3000
所有地区       总计         7500
月份小记       1月         3000
月份小记       2月         4500
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: