根据其他列中的最大值选择某列中的值

时间:2013-01-10 09:25:47

标签: oracle11g ranking

我有一张XYZ表

+------+------+------+-----+
|  X1  |  x2  |  x3  |  x4 |
+------+------+------+-----+
|  a   |   b  |  c   |  1  |
|  a   |   b  |  d   |  2  |
|  p   |   q  |  e   |  3  |
|  p   |   q  |  f   |  4  |
+------+------+------+-----+

条件是如果x1和x2匹配则获得x3和x4 x4最大的行 当我将查询此表时,我希望输出为

+------+------+------+-----+
|  X1  |  x2  |  x3  |  x4 |
+------+------+------+-----+
|  a   |   b  |  d   |  2  |
|  p   |   q  |  f   |  4  |
+------+------+------+-----+
我试过了 从XYZ t1中选择*, (从XYZ中选择x1,x2,max(x4))t2 其中t1.x1 = t2.x1和t1.x2 = t2.x2

但我想使用排名和分区等高级功能 因为这在大型数据库中速度很慢

1 个答案:

答案 0 :(得分:0)

可以使用rank或row_number,具体取决于在x4相等的情况下是否要返回多行。

例如:

SQL> select *
  2    from (select x1, x2, x3, x4, rank() over (partition by x1, x2 order by x4 desc) rnk
  3            from xyz)
  4   where rnk = 1;

X X X         X4        RNK
- - - ---------- ----------
a b d          2          1
p q f          4          1

但是如果a,b我们在x4 = 2时有两行,那么我们会得到两行:

SQL> insert into xyz values ('a', 'b', 'd', 2);

1 row created.

SQL> select *
  2    from (select x1, x2, x3, x4, rank() over (partition by x1, x2 order by x4 desc) rnk
  3            from xyz)
  4   where rnk = 1;

X X X         X4        RNK
- - - ---------- ----------
a b d          2          1
a b d          2          1
p q f          4          1

如果您只想要一个,请改用row_number()

SQL> select *
  2    from (select x1, x2, x3, x4, row_number() over (partition by x1, x2 order by x4 desc) rn
  3            from xyz)
  4   where rn = 1;

X X X         X4         RN
- - - ---------- ----------
a b d          2          1
p q f          4          1

SQL>