从列表中选择SQL PIVOT(在选择中)

时间:2011-05-19 14:49:31

标签: sql sql-server tsql pivot

是否可以执行PIVOT并从表中选择列表,而不是使用单个值?

像这样(语法错误不正确):

SELECT *
FROM (
    SELECT RepID, MilestoneID, ResultID FROM RM
) AS src
PIVOT (
    MAX(ResultID) FOR MilestoneID IN  (SELECT id FROM m) 
) AS pvt

这个编译,但对我不起作用:

SELECT *
FROM (
    SELECT RepID, MilestoneID, ResultID FROM RM
) AS src
PIVOT (
    MAX(ResultID) FOR MilestoneID IN  ([1], [2], [3], [4]) 
) AS pvt

PS:我不想使用动态SQL,有没有办法在不使用动态SQL的情况下执行此操作?

2 个答案:

答案 0 :(得分:11)

如果动态SQL出局,那么我担心答案是否定的,它无法完成。解析器需要预先知道值以执行到列的转移。

答案 1 :(得分:4)

可以做到。

DECLARE @idList varchar(500)
SET @idList = COALESCE(@idList + ',', '') + id
FROM m


DECLARE @sqlToRun varchar(1000)
SET @sqlToRun = '
SELECT * 
FROM ( 
    SELECT RepID, MilestoneID, ResultID FROM RM 
) AS src 
PIVOT ( 
    MAX(ResultID) FOR MilestoneID IN  ('+ @idList +')  
) AS pvt'   

EXEC (@sqlToRun)