gpt4 book ai didi

sql - 多次选择同一行

转载 作者:行者123 更新时间:2023-12-02 15:22:15 26 4
gpt4 key购买 nike

我有一个表,其中包含主对象的一些子对象。任何子项都可以出现多次,并且有一个包含该数字的 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, 1, 2 UNION ALL
SELECT 3, 2, 1 UNION ALL
SELECT 4, 2, 3

最佳答案

;with C as
(
select ChildID,
ParentID,
Occurences - 1 as Occurences
from @Children
union all
select ChildID,
ParentID,
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

关于sql - 多次选择同一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6608055/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com