-1

这是表结构:

Election
ElectionId ElectionName
1          12P
2          11G

History
ElectionId VoterId HowVoted
1          1       Rep
2          2       Dem
1          2       Non 

Voter
VoterId VoterName
1       Bill Smith
2       John Hearst

我想要这样的输出:

VoterName   12P  11P  note: Election names change so need to be pivoted dynamically
Bill Smith  Rep  Null
John Hearst Non  Dem    

我基本上需要将 ElectionNames 转为 Column Names,然后显示选民如何在行中投票。建议?谢谢!

4

1 回答 1

1

您可以使用动态 SQL 执行此操作,如下所示:

-- Get column names
DECLARE @Columns VARCHAR(MAX);  SET @Columns = '';
SELECT @Columns = @Columns + ', [' + ElectionName + ']' FROM Election;
SET @Columns = SUBSTRING(@Columns, 3, LEN(@Columns)) -- Remove the leading ', '

-- Declare dynamic SQL
DECLARE @sql VARCHAR(MAX);
SET @sql = 'WITH CTE AS
(
    SELECT VoterName, ElectionName, HowVoted
    FROM Election e
        INNER JOIN History h ON e.ElectionId = h.ElectionId
        INNER JOIN Voter v ON v.VoterId = h.VoterId
)
SELECT [VoterName], ' + @Columns + 'FROM CTE
PIVOT (MAX(HowVoted) FOR ElectionName IN ('+ @Columns + ')) AS p'

-- Run dynamic SQL
EXEC(@sql)
于 2012-07-11T21:10:47.273 回答