Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 显示选民投票方式的动态轴心_Sql Server_Tsql_Sql Server 2005_Pivot - Fatal编程技术网

Sql server 显示选民投票方式的动态轴心

Sql server 显示选民投票方式的动态轴心,sql-server,tsql,sql-server-2005,pivot,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 我希望输出如

以下是表格结构:

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    

我基本上需要将选民姓名转为列名,然后显示投票人在行中的投票方式。建议?谢谢

您可以使用动态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)

请显示样本数据和所需结果。另外,请使用
{}
正确突出显示代码示例,而不是

标记。您没有显示您尝试的内容?谢谢,它可以工作!接下来的问题是,如果我需要在CTE中添加where子句,例如where PRECINCTID=@PRECINCTID。我是不是用这个让自己敞开心扉接受注射攻击?如果有,是否有解决方法?请查看参数。