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 |
Sintwar
Starting Member
11 Posts |
Posted - 2009-08-20 : 22:26:11
|
I need data from a table like this:ID Item-------------------1 Car2 House3 Dog4 Cat5 Plane6 Trainto be returned like this:ID1 ID2 Item1 Item2-----------------------------------------1 2 Car House3 4 Dog Cat5 6 Plane TrainIs this possible? If so, how would this be done?Thanks! |
|
khtan
In (Som, Ni, Yak)
17689 Posts |
Posted - 2009-08-20 : 22:33:05
|
[code]DECLARE @sample TABLE( ID int, Item varchar(5))INSERT INTO @sampleSELECT 1, 'Car' UNION ALLSELECT 2, 'House' UNION ALLSELECT 3, 'Dog' UNION ALLSELECT 4, 'Cat' UNION ALLSELECT 5, 'Plane' UNION ALLSELECT 6, 'Train'SELECT ID1 = MIN(ID), ID2 = MAX(ID), Item1 = MAX(CASE WHEN ID % 2 = 1 THEN Item END), Item2 = MAX(CASE WHEN ID % 2 = 0 THEN Item END)FROM @sampleGROUP BY (ID - 1)/ 2/*ID1 ID2 Item1 Item2 ----------- ----------- ----- ----- 1 2 Car House3 4 Dog Cat5 6 Plane Train(3 row(s) affected)*/[/code] KH[spoiler]Time is always against us[/spoiler] |
|
|
Sintwar
Starting Member
11 Posts |
Posted - 2009-08-20 : 23:29:22
|
Cool khtan thanks!I ran into a problem with this method though. My ID's are not going to be in perfect order, so for example, if the ID order is 1,4,6,20,22,30, etc. instead of 1,2,3,4,5,6,etc., it breaks your script.I have attempted to remedy this by first creating a temporary table with it's own identity ID column, inserting the original data into that table, and then using your select command to extract the data from the temp table.Do you think this is a bit excessive? Or is there a better way to remedy this.Thanks! |
|
|
khtan
In (Som, Ni, Yak)
17689 Posts |
Posted - 2009-08-20 : 23:33:51
|
temp table is probably the best way for you. Unless you are using SQL 2005 / 2008 then you can make use of the row_number() function KH[spoiler]Time is always against us[/spoiler] |
|
|
Sintwar
Starting Member
11 Posts |
Posted - 2009-08-20 : 23:44:51
|
Awesome. Works for me. Thank for your help! |
|
|
|
|
|
|
|