日期:2014-05-17 浏览次数:20518 次
----------------------------
-- Author :fredrickhu(小F,向高手学习)
-- Date :2010-03-24 15:10:51
-- Verstion:
-- Microsoft SQL Server 2005 - 9.00.4035.00 (Intel X86)
-- Nov 24 2008 13:01:59
-- Copyright (c) 1988-2005 Microsoft Corporation
-- Developer Edition on Windows NT 5.1 (Build 2600: Service Pack 3)
--
----------------------------
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([Id] int,[Name] varchar(1),[Month] varchar(7),[Num] int)
insert [tb]
select 8,'A','2009-01',200 union all
select 9,'A','2009-02',300 union all
select 10,'A','2009-03',400 union all
select 11,'B','2009-01',200 union all
select 12,'B','2009-02',300 union all
select 13,'B','2009-03',400 union all
select 14,'A','2010-01',200
--------------开始查询--------------------------
select
isnull([name],'总计') as name,
sum(case [Month] when '2009-01' then num else 0 end ) as '2009-01',
sum(case [Month] when '2009-02' then num else 0 end ) as '2009-02',
sum(case [Month] when '2009-03' then num else 0 end ) as '2009-03',
sum(case when left([month],4)='2009' then num else 0 end) as '2009总计',
sum(case [Month] when '2010-01' then num else 0 end ) as '2010-01',
sum(case when left([month],4)='2010' then num else 0 end) as '2010总计'
from
tb t
group by
[name]
with rollup
----------------结果----------------------------
/* name 2009-01 2009-02 2009-03 2009总计 2010-01 2010总计
---- ----------- ----------- ----------- ----------- ----------- -----------
A 200 300 400 900 200 200
B 200 300 400 900 0 0
400 &nb