Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
snowbunny
Starting Member
5 Posts |
Posted - 2009-03-17 : 13:59:58
|
| Hi.I have two tables in a simple database:PricesID (int, identity, PK)Year (smallint - year of value)Quarter (smallint - year quarter 1-4)Area (smallint - FK to Areas.ID)Index (float)AreasID (int, identity, PK)Name (varchar)So, as you can see, the Prices table contains price information over time for certain areas. This might look like this:PricesID Year Quarter Area Index1 2000 1 1 1002 2000 2 1 1103 2000 3 1 1124 2000 4 1 1155 2000 1 2 2006 2000 2 2 2107 2000 3 2 2128 2000 4 2 215AreasID Name1 North2 SouthNow, what I would like to have returned from a query is the following:Year Quarter North South2000 1 100 2002000 2 110 2102000 3 112 2122000 4 115 215so, in other words, the row names from areas become column names.I'm sure this must be possible. Could someone point me in the correct direction?Thanks! |
|
|
vijayisonly
Master Smack Fu Yak Hacker
1836 Posts |
Posted - 2009-03-17 : 15:29:27
|
| If there are no too many distinct values for 'Area' maybe u can use this...declare @t table (id int,yr int,qrtr int, area int, indx int)insert @tselect 1, 2000, 1, 1, 100 union allselect 2, 2000, 2, 1, 110 union allselect 5, 2000, 1, 2, 200 union allselect 6, 2000, 2, 2, 210select yr,qrtr,max(case when area = 1 then indx else 0 end) as North,max(case when area = 2 then indx else 0 end) as Southfrom @t group by yr,qrtr |
 |
|
|
snowbunny
Starting Member
5 Posts |
Posted - 2009-03-17 : 15:45:10
|
| Thanks for your reply, but that's not quite what I want... the areas table is updatable, so the hard-coding way you suggest won't be scalable.I need some way of creating columns for each entry of the areas table at execution time. |
 |
|
|
matty
Posting Yak Master
161 Posts |
Posted - 2009-03-18 : 03:21:28
|
| You can use PIVOT..SELECT Yr,Quarter,MAX([North]) AS North,MAX([South]) AS SouthFROM( SELECT p.Yr,p.Quarter,p.area,p.indx,a.ID,a.Name FROM Prices p JOIN Areas a ON p.area = a.ID)Tpivot( MAX(indx) FOR Name IN ([North],[South])) AS pvtGROUP BY Quarter,YrYou may have to use dynamic sql if there are distinct values for 'Area' |
 |
|
|
snowbunny
Starting Member
5 Posts |
Posted - 2009-03-18 : 04:15:49
|
| Thanks for your reply. Again, I need to do this at execution time, without knowing the contents of the Area table. I suppose this could be achieved by building a SQL string and using spExecuteSQL, but unfortunately for this project, I am also restricted to SQL Server 2000, so PIVOT isn't available. I should have said that in my original question, sorry. |
 |
|
|
matty
Posting Yak Master
161 Posts |
Posted - 2009-03-18 : 05:37:23
|
| Refer http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=6216&whichpage=1 |
 |
|
|
|
|
|
|
|