选择每个组的第一行,使用ORDER BY多个列

时间:2012-07-11 01:56:49

标签: sql performance group-by sql-order-by sybase

我的表T包含xyab

SELECT x,y,a,b FROM T
ORDER BY x,y,a,b

给我下表

 x    | y    | a    | b
 x1   | y1   | a1   | b1
 x1   | y1   | a1   | b2
 x1   | y1   | a2   | b1
 x1   | y2   | a1   | b1
 x1   | y2   | a1   | b2
 x1   | y2   | a2   | b1

我如何获得每个x,y组的第一行?也就是说,我如何获得下表

 x    | y    | a    | b
 x1   | y1   | a1   | b1
 x1   | y2   | a1   | b1

这是第二个例子:对于表格T

 x    | y    | a    | b
 x1   | y1   | a1   | b3
 x1   | y1   | a1   | b4
 x1   | y1   | a2   | b1
 x1   | y1   | a2   | b2
 x1   | y2   | a1   | b3
 x1   | y2   | a1   | b4
 x1   | y2   | a2   | b1
 x1   | y2   | a2   | b2

我期待得到

 x    | y    | a    | b
 x1   | y1   | a1   | b3
 x1   | y2   | a1   | b3

4 个答案:

答案 0 :(得分:9)

考虑SQL 2005或更高版本:

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

答案 1 :(得分:3)

根据您的评论和新表结构,您可以使用这个简单的DBMS无关解决方案:

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

答案 2 :(得分:0)

这是一个非常有效的Oracle解决方案

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

答案 3 :(得分:0)

请试试这个并告诉我

select x,y,MIN(a) a,MIN(b) b
from T
group by X,y