将列转置为行

时间:2017-06-07 19:58:22

标签: sql sql-server pivot

我的表格看起来像这样

SurveyId    comments    val paramid
123     test1       100 1
123     test2       200 2
123     test3       300 3
456     test10      200 1
456     test20      150 2
456     test30      320 3

我期待类似下面基于paramid

的内容
surveyid    comments1   comments2   comments3   1   2   3
123     test1       test2       test3       100 200 300
456     test10      test20      test30      200 150 320

尝试使用枢轴如下

select * 
from 
(
SELECT       
     surveyid   
     ,val
      ,comments 
      ,paramid
  FROM sample_table where comments is not null and surveyid = 123
) a
pivot
(
  max([val])
  for [paramid] in ([1], [2], [3])
) piv;

有人可以建议上面的代码有什么问题吗?

1 个答案:

答案 0 :(得分:0)

你可以尝试这个..它很简单,只使用GROUP BY子句。(在MYSQL中尝试,它工作正常)

SELECT
surveyid
,MAX(comments1) AS comments1
,MAX(comments2) AS comments2
,MAX(comments3) AS comments3
,MAX(COL1) AS COL1
,MAX(COL2) AS COL2
,MAX(COL3) AS COL3
FROM
(
SELECT
surveyid
,CASE WHEN paramid=1 then comments else '' END AS comments1
,CASE WHEN paramid=2 then comments else '' END AS comments2
,CASE WHEN paramid=3 then comments else '' END AS comments3
,CASE WHEN paramid=1 then val else '' END AS COL1
,CASE WHEN paramid=2 then val else '' END AS COL2
,CASE WHEN paramid=3 then val else '' END AS COL3
FROM test.sample_table
) TMP
GROUP BY surveyid

结果: 123 test1 test2 test3 100 200 300 456 test10 test20 test30 200 150 320