sql – 多次选择同一行
发布时间:2021-03-07 09:50:57 所属栏目:编程 来源:网络整理
导读:我有一个表有一个主对象的孩子.任何子项都可以出现多次,并且有一个包含该数字的Occurences列,因此表中的数据类似于: ChildID | ParentID | Occurences------------------------------- 1 | 1 | 2 2 | 1 | 2 3 | 2 | 1 4 | 2 | 3 我需要得到所有孩子的清单,每
我有一个表有一个主对象的孩子.任何子项都可以出现多次,并且有一个包含该数字的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 (编辑:广西网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
站长推荐