根据包含B列中先前值的B列对A列进行排序

时间:2019-05-17 10:26:14

标签: sql sorting plsql lag lead

我想基于B列对A列进行排序,其中B列包含A列中的先前值。

这就是我所拥有的:

+----+----------+----------+
| ID |    A     |    B     |
+----+----------+----------+
|  1 | 17209061 |          |
|  2 | 53199491 | 51249612 |
|  3 | 61249612 | 17209061 |
|  4 | 51249612 | 61249612 |
+----+----------+----------+

这就是我想要的:

+----+----------+----------+----------+
| ID |    A     |    B     | Sort_seq |
+----+----------+----------+----------+
|  1 | 17209061 |          |        1 |
|  3 | 61249612 | 17209061 |        2 |
|  4 | 51249612 | 61249612 |        3 |
|  2 | 53199491 | 51249612 |        4 |
+----+----------+----------+----------+

我敢肯定有一种简单的方法可以做到这一点。你有什么想法吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

只需在lag()中使用order by

order by lag(a) over (order by id) nulls first

如果您想要一列,那么:

select t.id, t.a, t.prev_a,
       row_number() over (order by prev_a nulls first)
from (select t.*, lag(a) over (order by id) as prev_a
      from t
     ) t;