我有一个返回一些父记录和子记录的查询。我想以增量的方式为每个子记录返回一个唯一的id。因此,如果我有一个包含3个childs的记录和1个包含2个childs的记录,则希望返回。
Parent/Child | Parent_id | Child_id
1. Parent record, Parent_id, 0
2. child_record, Parent_Id, 1
3. child_record, Parent_Id, 2
4. child_record, Parent_Id, 3
5. Parent record, Parent_id, 0
6. child_record, Parent_Id, 1
7. child_record, Parent_Id, 2
对于如何从1生成child_id并递增1,然后为下一批子记录重新设置,您有什么想法吗?
发布于 2016-05-04 08:42:40
此查询根据其父id生成子编号:
select id_pk -- pk; defines global sort order
, p_c -- node type ('parent', 'child')
, p_id -- parent id
, row_number() over ( partition by p_id order by id_pk ) - 1 c_id
-- synthetic child id.
from test_pc
;
根据需要调整order by子句中的排序标准。
示例:(孩子之间的顺序并不重要,只需要一个唯一的本地id )
, row_number() over ( partition by p_id order by p_id, p_c desc ) - 1 c_id
https://stackoverflow.com/questions/37021896
复制相似问题