日期:2014-05-18 浏览次数:20630 次
use Tempdb
go
--> --> 
 
if not object_id(N'Tempdb..#T') is null
    drop table #T
Go
Create table #T([id] int,[price1] int,[price2] int,[bigclass] nvarchar(4),[smallclass] nvarchar(6),[year] int)
Insert #T
select 1,10,20,N'big1',N'small1','2011' union all
select 2,12,12,N'big1',N'small2','2011' union all
select 3,6,20,N'big2',N'small3','2011' union all
select 4,36,25,N'big3',N'small4','2011'
Go
declare @s nvarchar(4000)
set @s=''
Select     @s=@s+N','+quotename(smallclass+'price1')+N'=max(case when smallclass=N'+quotename(smallclass,'''')+N' then price1 else '''' end),'
                +quotename(smallclass+'price2')+N'=max(case when smallclass=N'+quotename(smallclass,'''')+N' then [price2] else '''' end)'
from #T group by smallclass
--顯示生成語句
print N'select year'+@s+N' from #T group by year'
exec(N'select year'+@s+N' from #T group by year')
go
/*
year    small1price1    small1price2    small2price1    small2price2    small3price1    small3price2    small4price1    small4price2
2011    10    20    12    12    6    20    36    25
*/