sql - 多次选择同一行

标签 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

最佳答案

;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/

相关文章:

sql - 如何在没有循环/游标的情况下组合两个表来分配销售量与需求

SQL Server : How to group by a datetime column based on a time interval (Such as within 2 hours)

mysql - 如何在执行 JOIN 查询后返回 NULL 时将 "Absent"设置为 Scannerid、DateTime 和 Status 等字段?

Java将日期转换为sql时间戳

sql - 在单个命令中有条件地更新表的多个列

sql - 统计和基数估计 - 为什么我会看到这个结果?

mysql - 通过 MS Access 97 进行 VBA 数据库更新时出现问题,记录锁定违规?

sql - 使用约束和默认值向现有 PostgreSQL 表添加一列

c# - 如何使用 App.config 连接 C# 和 Db?

python - SQL 中 GO 附近的语法不正确