sql server行转列

首先创建表和添加数据

想要的结果

--方法一
SELECT DISTINCT C.[USER_NAME] AS '姓名',
(SELECT SCORE FROM TEST_TB_GRADE WHERE [USER_NAME]=C.[USER_NAME] AND COURSE='语文') AS '语文',
(SELECT SCORE FROM TEST_TB_GRADE WHERE [USER_NAME]=C.[USER_NAME] AND COURSE='数学') AS '数学',
(SELECT SCORE FROM TEST_TB_GRADE WHERE [USER_NAME]=C.[USER_NAME] AND COURSE='英语') AS '英语'
FROM dbo.TEST_TB_GRADE C

--方法二
SELECT [USER_NAME] AS '姓名',
SUM(CASE WHEN COURSE='语文' THEN SCORE END) AS '语文',
SUM(CASE WHEN COURSE='数学' THEN SCORE END) AS '数学',
SUM(CASE WHEN COURSE='英语' THEN SCORE END) AS '英语'
FROM dbo.TEST_TB_GRADE
GROUP BY [USER_NAME]

--方法三
DECLARE @S NVARCHAR(1000)
SET @S='SELECT [USER_NAME] AS '''+'姓名'+''''
SELECT @S=@S+',SUM(CASE WHEN COURSE='''+CAST(COURSE AS VARCHAR)+'''THEN SCORE END) AS '''+COURSE+'''' FROM TEST_TB_GRADE GROUP BY COURSE
SET @S=@S+' FROM TEST_TB_GRADE GROUP BY [USER_NAME]'
EXEC(@S)

  推荐方法三

posted @ 2013-03-16 23:15  小银光  阅读(386)  评论(0编辑  收藏  举报