Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...