如何将2列转置为行

时间:2019-04-02 16:10:27

标签: sql sql-server

我目前有这张表用于调查,在这些调查中,我只需要答案和问题3的注释,而只需要问题4的注释。

+---------------------------------------------------+
| Employee | SurveyNo | Question | Answer | Comment |
+----------+----------+----------+--------+---------+
|   100    |    1     |    1     |Neutral |   NULL  |
|   100    |    1     |    2     |  Hard  |   NULL  |
|   100    |    1     |    3     |  Easy  |  asdfs  |
|   100    |    1     |    4     |  NULL  |  ssafa  |
|   200    |    2     |    1     |  Hard  |   NULL  |
|   200    |    2     |    2     |  Hard  |   NULL  |
|   200    |    2     |    3     |  Easy  |  asdfs  |
|   200    |    2     |    4     |  NULL  |   NULL  |
+---------------------------------------------------+

我正在寻找的是这样的

+--------------------------------------------------------------------------------+
| Employee | surveyNo |Question1 | Question2 | Question3 | CommentsQ3 | Comments |
+----------+----------+----------+-----------+-----------+------------+----------+
|   100    |    1     | Neutral  |    Hard   |   Easy    |   asdfs    |  ssafa   |
|   200    |    2     |   Hard   |    Hard   |   Easy    |   asdfs    |          |
+--------------------------------------------------------------------------------+

目前我能得到每个问题,但不能得到评论,我只想对问题3的评论和对问题4的评论。

但是当我包含评论时,我开始得到重复的行

SELECT  Employee,surveyNo,[1] as Question1,[2] as Question2,[3] as Question3
FROM
(
SELECT Employee,surveyNo,answer FROM Surveys WHERE Question in (1,2,3)
) d
pivot
(
max(answer)
for Question in ([1],[2],[3])
) piv
+--------------------------------------------------------+
| Employee | surveyNo |Question1 | Question2 | Question3 | 
+----------+----------+----------+-----------+-----------+
|   100    |    1     | Neutral  |    Hard   |   Easy    |
|   200    |    2     |   Hard   |    Hard   |   Easy    |
+--------------------------------------------------------+

1 个答案:

答案 0 :(得分:3)

您可以进行条件聚合:

SELECT Employee, surveyNo,
       MAX(CASE WHEN Question = 1 THEN Answer END) AS Question1 ,
       . . . 
       MAX(CASE WHEN Question = 1 THEN Comment END) AS CommentsQ1,
       . . .
FROM Surveys 
WHERE Question in (1,2,3)
GROUP BY Employee, surveyNo;