[英]Generate number in sql select statement
I have a query that returns some parent records and child records. 我有一个返回一些父记录和子记录的查询。 I would like to return for each child records a unique id by increment. 我想返回每个孩子记录一个增量的唯一ID。 So if i have a record with 3 childs and 1 with 2 childs would like to return. 因此,如果我有3个孩子的记录和1个有2个孩子的记录想要返回。
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
Any ideas of how to generate the child_id from 1 and increment by 1 and then reset again for next batch of child records? 有关如何从1生成child_id并递增1然后再次为下一批子记录重置的任何想法?
This query produces the child numbering contingent to their parent id: 此查询生成与其父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
;
Adjust the sorting criterion in the order by clause as needed. 根据需要在order by子句中调整排序标准。
Example: (order among children does not matter, just a unique local id is needed) 示例:(子项中的顺序无关紧要,只需要一个唯一的本地ID)
, row_number() over ( partition by p_id order by p_id, p_c desc ) - 1 c_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.