Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
962 views
in Technique[技术] by (71.8m points)

dynamic sql pivot in sql server

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, column1, column2,column3 from BUYSCTE ) BUY 

My table results running above query without the pivot is this

Column1 | Column2 | Column3| FYYear| Amount|

 1           cat     dog      2011   50 
 1           cat     dog      2012   75
 1           cat     dog      2013   65
 2          fish     snake    2011   23
 2          fish     snake    2012   39
 2          fish     snake    2013   59
 .. 
 ..  
 ..                           2016

so basically I want the results to end up like this:

Column1 | Column2 | Column3| 2011| 2012 | 2013 
 1           cat     dog      50    75     65
 2          fish     snake    23    39     59

so the query I came up with to make this happen is I first created a table variable and made it a dynamic variable and did a pivot like this,

declare @Year nvarchar(Max)
set @Year = STUFF(
(SELECT ', ' + quotename(FYYear)
from BUYSCTE Group By FYYear order by
FYYear For XML PATH(''))
, 1, 2, '');

The above populates the @Year value with: [2011], [2012], [2013], [2014], [2015], [2016]

I know that because I change the above select to SELECT @Year just to check if the value is set correctly

from there I change the above select after the table variable to

SELECT * from ( SELECT Amount, FYYear, column1, column2,column3 from BUYSCTE ) BUY 
PIVOT( SUM(Amount) FOR FYYear in ([@Year]) ) pvt

but my results end up being this

 Column1 | Column2 | Column3| @Year|
 1           cat     dog      null   
 2          fish     snake    null

What am I doing wrong? it seems like something small I am missing that I cannot see myself. even if I change the aggregate function from SUM to COUNT it gives 0 for the @Year column values instead of null

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...