问一个查询结果动态生成列的问题
现在碰到一个问题,如下:
入库表中,id为零部件的编号,内容举例
id shuliang date
1 400 2011-1-1
1 500 2011-1-1
1 200 2011-1-4
2 100 2011-1-5
。
。
。
。
希望可以通过SQL语句查询结果为
列名:id 2011-1-1 2011-1-4 2011-1-5 。。。(根据入库表中的时间再自动增加)
1 900 200 null
2 null null 100
可以实现么?
请赐教,谢谢!
[解决办法]
declare @sql varchar(max)set @sql = 'select id'select @sql = @sql + ',sum(case when convert(varchar(10),date,120) = '''+date+''' then isnull(shuliang,0) else 0 end) ['+date+']'from( select convert(varchar(10),date,120) as date from tb group by convert(varchar(10),date,120))tselect @sql = @sql + ' from tb group by id 'exec(@sql)
[解决办法]
declare @sql varchar(8000)set @sql = 'select id 'select @sql = @sql + ' , sum(case date when ''' + convert(varchar(10),date,120) + ''' then shuliang else null end) [' + convert(varchar(10),date,120) + ']'from (select distinct date from tb) as aset @sql = @sql + ' from tb group by id'exec(@sql)
[解决办法]
--> --> (Roy)生成測試數據 if not object_id('Tempdb..#T') is null drop table #TGoCreate table #T([id] int,[shuliang] int,[date] Datetime)Insert #Tselect 1,400,'2011-1-1' union allselect 1,500,'2011-1-1' union allselect 1,200,'2011-1-4' union allselect 2,100,'2011-1-5'Godeclare @s nvarchar(4000)set @s=''Select @s=@s+N','+quotename(CONVERT(varchar(10),Date,120))+N'=max(case when CONVERT(varchar(10),Date,120)=N'+quotename(CONVERT(varchar(10),Date,120),'''')+N' then shuliang end)'from #T group by date--顯示生成語句print N'select ID'+@s+N' from #T group by ID'exec(N'select ID'+@s+N' from #T group by ID')go/*ID 2011-01-01 2011-01-04 2011-01-051 500 200 NULL2 NULL NULL 100*/