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 |
|
Matt Greatorex
Starting Member
2 Posts |
Posted - 2005-06-29 : 12:26:01
|
| I'm hoping this will be an easy one for someone out there, but it's got me stumped.I have a table with a varying number of records in it. The structure is such that all columns hold a numeric value. I need to select the highest column value from each row and create a new table containing just these values. My problem is that I don't know how to identify each highest value, given that it could be in a different column for every row.Any suggestions gratefully received. |
|
|
SamC
White Water Yakist
3467 Posts |
Posted - 2005-06-29 : 12:33:33
|
| http://weblogs.sqlteam.com/brettk/archive/2005/05/25/5276.aspx |
 |
|
|
Matt Greatorex
Starting Member
2 Posts |
Posted - 2005-06-29 : 15:21:36
|
| I've been told to phrase the problem differently, so I hope this is okay. Apologies for any missing info.To create tables with a similar structure:Create table Table1(Col1 int, Col2 int, Col3 int)Create table Table2(Col1 int)I'm not sure on the best way to populate Table1, but as long as there are at least three rows and the numbers are all different, it will be sufficient. PerhapsInsert into Table1(Col1, Col2, Col3) Values (20,30,40,50,60,70,80,90,100)The code I'm trying to write would be something along the following lines, in the languages I can use. I just don't know how to phrase it in SQL:Fetch First from Table1Do while not EOT Table1Set high_val = Col1For col_count = 2 to 25 DoIf Col(col_count) > high_val thenhigh_val = Col(col_count)End IfEnd ForInsert into Table2.Col1 Values(high_val)Fetch Next from Table1End DoHopefully, this will result in Table2 consisting of the same number of rows as Table1, each containing the highest value from the corresponding row in Table1 e.g. 40, 70, 100 |
 |
|
|
SamC
White Water Yakist
3467 Posts |
Posted - 2005-06-29 : 15:52:05
|
There may be a much better way of doing this, but... I can brute force it with a temp table-- Number the rows in a working tableSELECT IDENTITY(INT, 1,1) As TID, COL1, COL2, COL3, ... COLNINTO #TempFROM Table1-- Collapse to a single columnSELECT TID, Col1 As Col INTO #Temp2 FROM #TempINSERT INTO #Temp2 (TID, Col) SELECT TID, COL2 FROM #Temp...INSERT INTO #Temp2 (TID, Col) SELECT TID, COLN FROM #Temp -- Last column-- Grand finale. Get the MAX from Each Row...SELECT MAX(Col) As MaxCol FROM #Temp2 GROUP BY TID-- Or, to insert this in another table...INSERT INTO Table2 (Col1) SELECT MAX(Col) As MaxCol FROM #Temp2 GROUP BY TID |
 |
|
|
|
|
|
|
|