请告诉我如何修改这个 SQL 选择以使用 pivot 而不是所有的 case 语句。
SELECT t.ProjectId,
COALESCE(MAX(ExecutiveChampion), 'n/a'),
COALESCE(MAX(BusinessOwner), 'n/a'),
COALESCE(MAX(BusinessAnalyst), 'n/a'),
COALESCE(MAX(GeneralContractor), 'n/a'),
COALESCE(MAX(PrimaryPM), 'n/a'),
COALESCE(MAX(DevelopmentManager), 'n/a'),
COALESCE(MAX(DevelopmentLead), 'n/a'),
COALESCE(MAX(TDM), 'n/a'),
COALESCE(MAX(PTM), 'n/a')
FROM (
SELECT pl.ProjectId,
CASE WHEN StakeholderCID = 95 THEN FullName ELSE NULL END as 'ExecutiveChampion',
CASE WHEN StakeholderCID = 96 THEN FullName ELSE NULL END as 'BusinessOwner',
CASE WHEN StakeholderCID = 97 THEN FullName ELSE NULL END as 'BusinessAnalyst',
CASE WHEN StakeholderCID = 100 THEN FullName ELSE NULL END as 'GeneralContractor',
CASE WHEN StakeholderCID = 101 THEN FullName ELSE NULL END as 'PrimaryPM',
CASE WHEN StakeholderCID = 102 THEN FullName ELSE NULL END as 'DevelopmentManager',
CASE WHEN StakeholderCID = 103 THEN FullName ELSE NULL END as 'DevelopmentLead',
CASE WHEN StakeholderCID = 104 THEN FullName ELSE NULL END as 'TDM',
CASE WHEN StakeholderCID = 105 THEN FullName ELSE NULL END as 'PTM'
FROM @pList pl
INNER JOIN StatusCode sc
ON 1 = 1
AND SCID IN (8, 9)
LEFT OUTER JOIN ProjectStakeholder ps
ON pl.ProjectId = ps.ProjectId
AND sc.CID = ps.StakeholderCID
) as t
GROUP BY t.ProjectId
调整留给请求者作为练习。
使用 PIVOT 和 UNPIVOT
完整答案如下: