日期:2014-05-18 浏览次数:20757 次
--> 测试数据:[test]
go
if object_id('[test]') is not null
drop table [test]
go
create table [test](
[GoodsId] int,
[GoodsName] varchar(1),
[Date] date,
[Qty] int
)
go
insert [test]
select 1,'a','2012/03/10',100 union all
select 1,'a','2012/03/17',100 union all
select 1,'a','2012/03/24',100 union all
select 1,'a','2012/03/31',100 union all
select 2,'b','2012/04/07',100 union all
select 2,'b','2012/04/14',100 union all
select 2,'b','2012/04/21',100 union all
select 2,'b','2012/04/28',100 union all
select 1,'a','2012/04/07',100 union all
select 1,'a','2012/04/14',100 union all
select 1,'a','2012/04/21',100 union all
select 1,'a','2012/04/28',100
declare @str varchar(max)
set @str=''
select @str=@str+','+quotename([Date],'')+'=max(case when [Date]='+QUOTENAME([Date],'''')+'
then [Qty] else 0 end)' from(select [GoodsId],[GoodsName],convert(varchar(5),[Date],101)[Date],
[Qty] from test
union all select [GoodsId],[GoodsName],'['+ltrim(DATEPART(MM,[Date]))+'月份]' as [Date],
SUM([Qty]) [Qty] from test group by [GoodsId],[GoodsName],'['+ltrim(DATEPART(MM,[Date]))+'月份]')a
group by [Date]
set @str='select [GoodsId],[GoodsName]'+@str+' from
(select [GoodsId],[GoodsName],convert(varchar(5),[Date],101)[Date],
[Qty] from test
union all select [GoodsId],[GoodsName],''[''+ltrim(DATEPART(MM,[Date]))+''月份]'' as [Date],
SUM([Qty]) [Qty] from test group by [GoodsId],[GoodsName],''[''+ltrim(DATEPART(MM,[Date]))+''月份]'')a
group by [GoodsId],[GoodsName]'
exec(@str)
/*
GoodsId GoodsName 03/10 03/17 03/24 03/31 [3月份] 04/07 04/14 04/21 04/28 [4月份]
1 a 100 100 100 100 400 100 100 100 100 400
2 b 0 0 0 0 0 100 100 100 100 400
*/