Selecting the first row from each group, with ORDER BY more than one column

笑着哭i 提交于 2019-12-05 17:19:57

Considering SQL 2005 or Above:

SELECT T1.X,
       T1.Y,
       T1.A,
       T1.B
  FROM
      (SELECT X,
              Y,
              A,
              B,
              ROW_NUMBER() OVER (Partition BY X,Y Order By A,B) AS RowNum
         FROM T
     ) T1
WHERE T1.RowNum = 1

As per your comments and new table structure, you can use this simple DBMS-agnostic solution:

SELECT a.x,a.y,a.a,MIN(a.b) b
FROM T a
JOIN ( SELECT x,y,MIN(a) a FROM T GROUP BY x,y ) b ON
    a.x = b.x AND
    a.y = b.y AND
    a.a = b.a
GROUP BY a.x,a.y,a.a

SQL-Fiddle Demo

Here is a very efficient Oracle solution

select x, 
       y, 
       min(a) as a, 
       min(b) keep( dense_rank first order by a) as b
  from T
 group by x,y

please try this and let me know

select x,y,MIN(a) a,MIN(b) b
from T
group by X,y
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!