Selecting the first row from each group, with ORDE

2019-05-05 03:44发布

问题:

I have a table T with columns x,y,a,b such that

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

gives me the following table

 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

How would I get the first row of each x,y group? That is, how would I get the following table

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

Here is a second example: For a table T such that

 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

I am expecting to get

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

回答1:

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


回答2:

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



回答3:

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


回答4:

please try this and let me know

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