多次选择同一行

时间:2011-07-07 08:52:50

标签: sql sql-server tsql

我有一个包含主对象子节点的表。任何子项都可以出现多次,并且有一个包含该数字的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

2 个答案:

答案 0 :(得分:7)

;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

答案 1 :(得分:4)

;WITH CTEs
AS
(
    SELECT 1 [Id]
    UNION ALL
    SELECT [Id] + 1 FROM CTEs WHERE [Id] < 100
)
SELECT ROW_NUMBER() OVER(ORDER BY c1.ChildID, c1.ParentID) [rn]
    , c1.ChildID, c1.ParentID
FROM CTEs ct
JOIN @Children c1 ON c1.Occurences >= ct.[Id]

生成序列的另一种方法是使用预定义表,例如master.dbo.spt_values

SELECT ROW_NUMBER() OVER(ORDER BY c1.ChildID, c1.ParentID) [rn]
    , c1.ChildID, c1.ParentID
FROM master.dbo.spt_values ct
JOIN @Children c1 ON c1.Occurences > ct.number
    AND ct.type = 'P'