【发布时间】:2018-09-03 09:57:30
【问题描述】:
我正在尝试在 SQL 中转换以下数据集。
SELECT ParticipantID,
ContactReasonTypeID,
Completed = CASE WHEN Returned IS NOT NULL
THEN 'Completed'
ELSE 'Not completed'
END
FROM ContactReason
WHERE ContactReasonTypeID = 40 -- M4
UNION
SELECT ParticipantID,
ContactReasonTypeID,
Completed = CASE WHEN Returned IS NOT NULL
THEN 'Completed'
ELSE 'Not completed'
END
FROM ContactReason
WHERE ContactReasonTypeID = 80 -- M8
结果如下:
ParticipantID | QuestionnaireID | Completed
1 40 'Completed'
1 80 'Not completed'
2 40 'Completed'
2 80 'Completed'
3 40 'Completed'
3 80 'Not completed'
4 40 'Completed'
4 80 'Not completed'
我想要的是像这样旋转结果(其中 M4 是 QuestionnaireID 40,M8 是 80):
ParticipantID | M4 | M8
1 'Completed' 'Not completed'
2 'Completed' 'Completed'
3 'Completed' 'Not completed'
4 'Completed' 'Not completed'
我正在为如何旋转表格而苦苦挣扎。我当前的 SQL 如下并导致错误。我尝试根据其他帖子切换列,但无法确定需要什么:
SELECT *
FROM (
SELECT ParticipantID,
ContactReasonTypeID,
Completed = CASE WHEN Returned IS NOT NULL
THEN 'Completed'
ELSE 'Not completed'
END
FROM ContactReason
WHERE ContactReasonTypeID = 40
UNION
SELECT ParticipantID,
ContactReasonTypeID,
Completed = CASE WHEN Returned IS NOT NULL
THEN 'Completed'
ELSE 'Not completed'
END
FROM ContactReason
WHERE ContactReasonTypeID = 80
) AS tbl
PIVOT (
MAX(Returned)
FOR ContactReasonTypeID IN ([M4],[M8])
) AS pvt
ORDER BY ParticipantID
【问题讨论】:
标签: sql sql-server tsql pivot