Less Than Dot is a community of passionate IT professionals and enthusiasts dedicated to sharing technical knowledge, experience, and assistance. Inside you will find reference materials, interesting technical discussions, and expert tips and commentary. Once you register for an account you will have immediate access to the forums and all past articles and commentaries.
Returning The Maximum Value For A Row
From Wiki
You want to return the maximum value for a column and all the other columns for that table, How can you do that? First create this table
- CREATE TABLE #MaxVal(id INT,VALUE INT,OtherCol CHAR(1))
- INSERT #MaxVal VALUES(1,1,'A')
- INSERT #MaxVal VALUES(1,2,'A')
- INSERT #MaxVal VALUES(1,3,'Z')
- INSERT #MaxVal VALUES(2,1,'A')
- INSERT #MaxVal VALUES(2,2,'X')
- INSERT #MaxVal VALUES(2,3,'A')
- INSERT #MaxVal VALUES(3,1,'A')
- INSERT #MaxVal VALUES(3,2,'Y')
If you only are interested in the id plus the maximum value of a column it is pretty easy; you just do MAX and GROUP BY.
- SELECT id,MAX(VALUE) AS VALUE
- FROM #MaxVal
- GROUP BY id
Output
| ID | Value |
| 1 | 3 |
| 2 | 3 |
| 3 | 2 |
If you need the whole row then you join the table with the group by subquery
- SELECT t.* FROM(
- SELECT id,MAX(VALUE) AS MaxValue
- FROM #MaxVal
- GROUP BY id) x
- JOIN #MaxVal t ON x.id =t.id
- AND x.MaxValue =t.VALUE
Output
| ID | Value | OtherCol |
| 3 | 2 | Y |
| 2 | 3 | A |
| 1 | 3 | Z |
Contributed by: --SQLDenis 02:40, 31 May 2008 (GMT)
Part of SQL Server Programming Hacks
Section Ranking, Max etc



LTD Social Sitings
Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.