Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 
        
Home       Members    Calendar    Who's On


Add to briefcase

pivot query help Expand / Collapse
Author
Message
Posted Thursday, October 22, 2009 8:01 AM
SSC Rookie

SSC RookieSSC RookieSSC RookieSSC RookieSSC RookieSSC RookieSSC RookieSSC Rookie

Group: General Forum Members
Last Login: Friday, June 22, 2012 8:00 AM
Points: 44, Visits: 282
This is my query

select year, ID, val
from table1 t1
left join table2 t2 on t1.companyid = t2.companyid

the output of the query is :

year    ID      val

2008 7 NULL
2009 7 0.00
2010 7 0.00
2011 7 0.00
2008 8 NULL
2009 8 0.00
2010 8 0.00
2011 8 0.00


now i want to pivot this table to get the output as below

year    7      8
2008 null null
2009 0.00 0.00
2010 0.00 0.00
2011 0.00 0.00


Now there can be many numbers of companyid so the number of colums in the final pivot query will increase or decrease based on distinct Id numbers.

Can you please help me with this.

thanks
Post #807191
Posted Thursday, October 22, 2009 9:38 AM


Mr or Mrs. 500

Mr or Mrs. 500Mr or Mrs. 500Mr or Mrs. 500Mr or Mrs. 500Mr or Mrs. 500Mr or Mrs. 500Mr or Mrs. 500Mr or Mrs. 500

Group: General Forum Members
Last Login: Tuesday, August 02, 2011 3:36 AM
Points: 579, Visits: 1,803
Sorry, I aint givin the complete solution. This I guess you would anyway have it. I am really interested to know how anyone will approach this other part of the problem (unknown number of pivot columns)

CREATE TABLE #T3(iYear int, ID int , Val float)

INSERT INTO #T3 VALUES (2008, 7, NULL)
INSERT INTO #T3 VALUES (2009, 7, 0.0)
INSERT INTO #T3 VALUES (2010, 7, 0.0)
INSERT INTO #T3 VALUES (2011, 7, 0.0)
INSERT INTO #T3 VALUES (2008, 8, NULL)
INSERT INTO #T3 VALUES (2009, 8, 0.0)
INSERT INTO #T3 VALUES (2010, 8, 0.0)
INSERT INTO #T3 VALUES (2011, 8, 0.0)

select
iYear, [7], [8]
from #t3 T
PIVOT (sum(Val) FOR ID IN ([7],[8])) PVT



---------------------------------------------------------------------------------
Post #807262
Posted Thursday, October 22, 2009 7:38 PM


SSCommitted

SSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommitted

Group: General Forum Members
Last Login: 2 days ago @ 9:38 AM
Points: 1,525, Visits: 4,071
You basically need to use dynamic SQL to generate the columns for the pivot. Jeff wrote an article on it here:

http://www.sqlservercentral.com/articles/Crosstab/65048/



Seth Phelabaum
Consistency is only a virtue if you're not a screwup.

Links: How to Post Sample Data :: Running Totals :: Tally Table :: Cross Tabs/Pivots :: String Concatenation
Post #807546
« Prev Topic | Next Topic »

Add to briefcase

Permissions Expand / Collapse