Oracle自定义行计数器重置

uajslkp6  于 2023-08-04  发布在  Oracle
关注(0)|答案(1)|浏览(98)

我想在Oracle中按组创建行计数器列,但我想根据先前记录中的值重置此计数器。
例如:

+----------+---------+
| ID       | val     |
+----------|---------|
|123       | 1       |
|123       | null    |
|123       | 1       |
|123       | null    |
|123       | 1       |
|123       | null    |
|123       | null    |
|123       | null    |
| ...      | ....    |
+----------+---------+

字符串
我想要的:

+----------+---------+
| ID       |         |
+----------|---------|
|123       | 1       |
|123       | 2       |
|123       | 1       |
|123       | 2       |
|123       | 1       |
|123       | 2       |
|123       | 3       |
|123       | 4       |
|123       | 5       |
|...       | ...     |
+----------+---------+

6rqinv9w

6rqinv9w1#

SQL表表示无序集合,因此假设您的表应该已经有一个用于排序的列,即称之为row_id,其唯一定义的值为1,2,3,4,5,6,7,8,9...当我们想要生成一个新的列,其中每个非空值都重置递增的值,然后考虑下面的SUM()解析函数最近用作ROW_NUMBER()函数内的分区标准,例如

SELECT id, ROW_NUMBER() OVER (PARTITION BY part ORDER BY row_id) AS new_row_id
  FROM( SELECT t.*, 
               SUM(NVL2(val,1,0)) OVER (ORDER BY row_id) AS part
          FROM t)
 ORDER BY row_id

字符串
Demo

相关问题