0

I have a table XYZ as

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

condition is if x1 and x2 matches then get x3 and x4 of row where x4 is maximum when i will query this table I want to get output as

+------+------+------+-----+
|  X1  |  x2  |  x3  |  x4 |
+------+------+------+-----+
|  a   |   b  |  d   |  2  |
|  p   |   q  |  f   |  4  |
+------+------+------+-----+

i tried as select * from XYZ t1, (select x1,x2,max(x4) from XYZ ) t2 where t1.x1=t2.x1 and t1.x2=t2.x2

but i want to use advance functions like rank and partations as this is much slow in large database

4

1 回答 1

0

在 x4 相等的情况下,根据是否要返回多行,可以使用 rank 或 row_number。

例如:

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>
于 2013-01-10T09:52:22.893 回答