我有一个包含两列的表格(让我们将其命名为 person)
id, parent_id
我想枚举每条记录,但为每条记录分配一个子编号,其中parent_id不为空,例如
id | parent_id| number
1 NULL 1
2 NULL 2
3 2 2.1
4 NULL 3
5 4 3.1
parent 应该有按 id
顺序排列的连续编号, child - 每个 parent 都有从 1 开始的连续编号。一个 parent 可能有很多 child 。但 child 不能生 child ,所以3.3.3不是一个案例。
实现这一目标的最佳方法是什么?
最佳答案
我会使用窗口函数来做到这一点:
select t.*,
concat_ws('.',
dense_rank() over (order by coalesce(parent_id, id)),
(case when parent_id is not null
then row_number() over (partition by parent_id order by id)
end)
)
from person t
order by id;
关于sql - 具有非标准编号的父子关系的枚举表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54390312/