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 |
|
udaymahajan
Starting Member
17 Posts |
Posted - 2009-04-28 : 09:48:04
|
| My table is as followstable name : YearRecord,and columns are Years,Populationdata inside on that table isYearRecord===================Years Population2001 10002002 5002003 20002004 3000now i want to display output as followsYears Ratio2002-2001 -5002003-2002 15002004-2003 1000so how can i design Sql Query to show this outputuday |
|
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2009-04-28 : 09:54:47
|
[code]DECLARE @Sample TABLE ( Years SMALLINT, Population INT )INSERT @SampleSELECT 2001, 1000 UNION ALLSELECT 2002, 500 UNION ALLSELECT 2003, 2000 UNION ALLSELECT 2004, 3000-- PesoSELECT aYear, MAX(bYear), SUM(pop)FROM ( SELECT Years AS aYear, NULL AS bYear, Population AS pop FROM @Sample UNION ALL SELECT Years + 1 AS aYear, Years AS bYear, -Population AS pop FROM @Sample ) AS dGROUP BY aYearHAVING COUNT(*) = 2ORDER BY aYear[/code] E 12°55'05.63"N 56°04'39.26" |
 |
|
|
ayamas
Aged Yak Warrior
552 Posts |
Posted - 2009-04-28 : 09:59:19
|
| Peso are there any shortcomings if a query like this is used?declare @Table_X table( Years varchar(10), Pop int)Insert into @Table_Xselect 2001 ,1000 union allselect 2002 ,500 union allselect 2003 ,2000 union allselect 2004 ,3000select t1.Years + '-' + t2.Years as Years,t1.Pop-t2.Pop as Ratio from @Table_X t1inner join @Table_X t2 on t1.Years=t2.Years+1 |
 |
|
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2009-04-28 : 10:02:47
|
There could be a performance penalty if the number of records are large.It takes some CPU to build the hash table for joining.See this topic for comparison for JOIN and UNION ALL with moving average http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=93911 E 12°55'05.63"N 56°04'39.26" |
 |
|
|
ayamas
Aged Yak Warrior
552 Posts |
Posted - 2009-04-28 : 10:29:41
|
quote: Originally posted by Peso There could be a performance penalty if the number of records are large.It takes some CPU to build the hash table for joining.See this topic for comparison for JOIN and UNION ALL with moving average http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=93911 E 12°55'05.63"N 56°04'39.26"
It does works faster. |
 |
|
|
|
|
|
|
|