我目前有这个用于调查的表,我只需要对问题No3的回答和评论的评论以及对问题No4的评论
+---------------------------------------------------+
| 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 |
+--------------------------------------------------------+
你可以做条件聚合:
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;