dynamic sql pivot in sql server

前端 未结 1 1186
说谎
说谎 2020-12-02 01:24

Running this query in sql server 2008 now, but soon plan to move it in creating a report in sql reporting services:

SELECT * from ( SELECT Amount, Year, col         


        
相关标签:
1条回答
  • 2020-12-02 01:48

    You are close, but for this to work you have to construct your PIVOT using dynamic SQL and then execute it. So, after you populate your variable @Year, you need to do something like this:

    DECLARE @Query VARCHAR(MAX)
    
    SET @Query = '
    SELECT * from ( SELECT Amount, FYYear, column1, column2,column3 from BUYSCTE ) BUY 
    PIVOT( SUM(Amount) FOR FYYear in ('+ @Year + ') ) pvt'
    
    EXEC(@Query)
    

    Though before doing this, you should take a look at this link.

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