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.

LTD Social Sitings

Lessthandot twitter Lessthandot Linkedin Lessthandot facebook Lessthandot rss

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

Returning The Maximum Value For A Row

From Wiki

Jump to: navigation, search

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

  1. CREATE TABLE #MaxVal(id INT,VALUE INT,OtherCol CHAR(1))
  2.     INSERT #MaxVal VALUES(1,1,'A')
  3.     INSERT #MaxVal VALUES(1,2,'A')
  4.     INSERT #MaxVal VALUES(1,3,'Z')
  5.     INSERT #MaxVal VALUES(2,1,'A')
  6.     INSERT #MaxVal VALUES(2,2,'X')
  7.     INSERT #MaxVal VALUES(2,3,'A')
  8.     INSERT #MaxVal VALUES(3,1,'A')
  9.     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.

  2.     FROM #MaxVal
  3.     GROUP BY id


ID Value
1 3
2 3
3 2

If you need the whole row then you join the table with the group by subquery

  1. SELECT t.* FROM(
  2.     SELECT id,MAX(VALUE) AS MaxValue
  3.     FROM #MaxVal
  4.     GROUP BY id) x
  5.     JOIN #MaxVal t ON x.id =t.id
  6.     AND x.MaxValue =t.VALUE


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

137 Rating: 2.5/5 (104 votes cast)