SQL PIVOT SELECT FROM LIST (IN SELECT)

后端 未结 2 556
伪装坚强ぢ
伪装坚强ぢ 2020-12-17 14:24

Is it possible to do a PIVOT and select list from a table, instead of using single values?

Like this (incorrect syntax error):

SELECT *
FROM (
    SE         


        
相关标签:
2条回答
  • 2020-12-17 15:10

    It Can be done.

    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)
    
    0 讨论(0)
  • 2020-12-17 15:18

    If dynamic SQL is out then I'm afraid the answer is no, it can't be done. The parser needs to know the values up front to perform the pivot to columns.

    0 讨论(0)
提交回复
热议问题