小编典典

从每个组中选择第一行,其中ORDER BY多于一列

sql

我有一个表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

阅读 161

收藏
2021-04-22

共1个答案

小编典典

考虑到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
2021-04-22