How to order values inside group by

Consider the following SQL Server table:

  ID  |   X   |   Y
------+-------+-------
   1  |   1   |   1
   2  |   1   |   2
   3  |   1   |   3
   4  |   2   |   40
   5  |   2   |   500
   6  |   3   |   1
   7  |   3   |   100
   8  |   3   |   10

I need to select the ID of the row that has the maximum value of Y grouped by x, i.e:

  ID  |   X   |   Y
------+-------+-------
   3  |   1   |   3
   5  |   2   |  500
   7  |   3   |  100

The query will be nested several times so an optimal performance solution is required...

Answers


Setup:

 declare @MyTable table(ID int, X int, Y int)

 insert @MyTable
 values
    (   1  ,   1   ,   1),
    (   2  ,   1   ,   2),
    (   3  ,   1   ,   3),
    (   4  ,   2   ,   40),
    (   5  ,   2   ,   500),
    (   6  ,   3   ,   1),
    (   7  ,   3   ,   100),
    (   8  ,   3   ,   10)

Query:

;with cte
as
(
    select *, row_number() over(partition by X order by Y desc) RowNumber
    from @MyTable
)
select Id, X, Y
from cte
where RowNumber = 1

Result:

Id          X           Y
----------- ----------- -----------
3           1           3
5           2           500
7           3           100

The query is for MS SQL 2005+. The setup will work in MS SQL 2008+.


Yeah, many times this type of question... Added keyword "STRAIGHT_JOIN" to pre-optimize the query by enforcing the "PreQuery" first.

select STRAIGHT_JOIN
      YT.*
   from 
      ( select x, max(y) HighPerX
           from YourTable 
           group by x ) PreQuery
      join
         YourTable YT
            on PreQuery.X = YT.X 
            AND PreQuery.HighPerX = YT.y

This is a classic:

The Rows Holding the Group-wise Maximum of a Certain Column


Also see what you can do with row_number() function http://beyondrelational.com/blogs/madhivanan/archive/2007/08/27/multipurpose-row-number-function.aspx


Need Your Help


About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.