SQL 语句实现行转列

CREATE TABLE #tempcloum(
    [productNum] varchar(20)  null,
    [year1] decimal not null,
    [year2] decimal not null,
    [year3] decimal not null    
)
--лляD┴л
DECLARE @sql VARCHAR(800)
SET @sql = 'SELECT [productNum],'   
SELECT @sql = @sql + 'SUM(CASE [year] WHEN '''+[year]+''' THEN [price] ELSE 0 END) AS '''+[year]+''','   
FROM (SELECT DISTINCT [year] FROM #tempYear) AS a     
SELECT @sql = LEFT(@sql,LEN(@sql)-1) + ' FROM #tempYear  GROUP BY [productNum] '
PRINT(@sql)

insert into #tempcloum
   
EXEC(@sql)
GO

 

posted @ 2018-04-03 16:22  程序员不帅哥  阅读(178)  评论(1编辑  收藏  举报