动态枢轴显示选民如何投票

时间:2012-07-11 20:39:36

标签: sql-server tsql sql-server-2005 pivot

这是表结构:

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转移到列名称,然后显示选民如何在该行中投票。建议?谢谢!

1 个答案:

答案 0 :(得分: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)