动态列
declare @sql1 varchar(8000)
set @sql1='select ProductId as ''型号'''
select @sql1=@sql1+',max(case d.id1 when '''+c.id1+''' then d.Price else 0 end) as ['+'列'+id1+']'
from (select cast(id1 as varchar(1000)) as id1 from (select a.*,id1=ROW_NUMBER()
OVER(partition by ProductId order by KeyinDate desc) from ZK_SAL_ModelPrice a) b group by id1) as c select @sql1=@sql1
+'from (select a.*,id1=ROW_NUMBER() over(partition by ProductId order by KeyinDate desc) from ZK_SAL_ModelPrice a)d group by d.ProductId'
exec (@sql1)
静态列
select ProductId as 'ProductId'
,max(case d.id1 when '1' then d.Price else 0 end) as [col1]
,max(case d.id1 when '2' then d.Price else 0 end) as [col2]
,max(case d.id1 when '3' then d.Price else 0 end) as [col3]
,max(case d.id1 when '4' then d.Price else 0 end) as [col4]
,max(case d.id1 when '5' then d.Price else 0 end) as [col5]
,max(case d.id1 when '6' then d.Price else 0 end) as [col6]
,max(case d.id1 when '7' then d.Price else 0 end) as [col7]
,max(case d.id1 when '8' then d.Price else 0 end) as [col8]
,max(case d.id1 when '9' then d.Price else 0 end) as [col9]
,max(case d.id1 when '10' then d.Price else 0 end) as [col10]
INTO #table1
FROM (select a.*,id1=ROW_NUMBER() over(partition by ProductId order by KeyinDate desc) from ZK_SAL_ModelPrice a)d
GROUP by d.ProductId