sql – 多次选择同一行

我有一个表有一个主对象的孩子.任何子项都可以出现多次,并且有一个包含该数字的Occurences列,因此表中的数据类似于:
ChildID | ParentID | Occurences
-------------------------------
      1 |        1 |        2
      2 |        1 |        2
      3 |        2 |        1
      4 |        2 |        3

我需要得到所有孩子的清单,每个孩子在结果中出现核心次数,例如

IDENT | ChildID | ParentID
--------------------------
    1 |       1 |        1
    2 |       1 |        1
    3 |       2 |        1
    4 |       2 |        1
    5 |       3 |        2
    6 |       4 |        2
    7 |       4 |        2
    8 |       4 |        2

我可以使用一个循环表的游标并插入尽可能多的行,但我认为这不是最好的解决方案.

谢谢您的帮助

创建脚本包括

DECLARE @Children TABLE (ChildID int,ParentID int,Occurences int)

INSERT  @Children
SELECT  1,1,2 UNION ALL
SELECT  2,2 UNION ALL
SELECT  3,2,1 UNION ALL
SELECT  4,3

解决方法

;with C as
(
  select ChildID,ParentID,Occurences - 1 as Occurences
  from @Children
  union all
  select ChildID,Occurences - 1 as Occurences
  from C
  where Occurences > 0
)
select row_number() over(order by ChildID) as IDENT,ChildID,ParentID
from C
order by IDENT

相关文章

SELECT a.*,b.dp_name,c.pa_name,fm_name=(CASE WHEN a.fm_n...
if not exists(select name from syscolumns where name=&am...
select a.*,pano=a.pa_no,b.pa_name,f.dp_name,e.fw_state_n...
要在 SQL Server 2019 中设置定时自动重启,可以使用 Window...
您收到的错误消息表明数据库 'EastRiver' 的...
首先我需要查询出需要使用SQL Server Profiler跟踪的数据库标...