mssql2005 cube和grouping的分组统计

SQL语句练习使用cube和grouping的分组统计。

 

代码
   
     
-- ----------------------------------------------------------------------
--
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



你可能感兴趣的:(sql2005)