日期:2014-05-17 浏览次数:20428 次
select 客户 ,
sum(case when 月份=1 then 月销售额 else 0 end) as 1月销售额,
sum(case when 月份=2 then 月销售额 else 0 end) as 2月销售额,
sum(case when 月份=3 then 月销售额 else 0 end) as 3月销售额,
...
sum(case when 月份=12 then 月销售额 else 0 end) as 12月销售额,
sum(月销售额) as 总销售额,
from tb
group by 客户
create table #tb(客户名称 varchar(10), 月份 int,月销售额 numeric(12,2))
insert into #tb
select '王五',1,100
union all select '王五',2,80
union all select '王五',3,85
union all select '王五',4,90
union all select '王五',5,105
union all select '王五',6,110
union all select '李四',1,NULL
union all select '李四',2,NULL
union all select '李四',3,NULL
union all select '李四',4,50
union all select '李四',5,55
union all select '李四',6,60
union all select '李四',7,NULL
union all select '李四',8,80
union all select '李四',9,10
--方法二(一般用在sql server2000)
declare @sql varchar(8000)
set @sql=''
select @sql=@sql + ',['+rtrim(月份)+'月销售额]=sum(case rtrim(月份) when '''+rtrim(月份)+''' then 月销售额 end)'
from #tb group by rtrim(月份)