根据另一个 table 的 INT 在 SELECT 中创建行

Creating rows in a SELECT based on INT from another table

假设我有一个名为 'contracts' 的 table,它有一列 'NumYears'.

例如

SELECT 
    ClientId,
    NumYears
FROM Contracts

ClientId NumYears
-------- -----------
123456789    5
987654321    3

我有另一个 table 'contract_reviews' 可以通过 ClientId 加入合同。

每年都会要求用户查看存档的信息,完成后会在 'contract_reviews'

中插入一个新行
SELECT
    ClientId,
    Reviewed,
    YearFor,
    OtherColumn
FROM Contract_Reviews

ClientId  Reviewed    YearFor OtherColumn
--------- ----------- ------- -----------
123456789 1           2018    '£100'
123456789 1           2019    '£100'

客户'123456789'可能是第二年,所以'contract_reviews'只会保留2条记录。到 'NumYears' 结束时,我们应该期望 5.

基本上,我需要 select 来自 'contract_reviews' 的所有行并为缺失的 'contract_reviews' 生成新的空行,最多 'NumYears'

ClientId  Reviewed    YearFor OtherColumn
--------- ----------- ------- -----------
123456789 1           2018    '£100'
123456789 1           2019    '£100'
123456789 0           NULL    NULL
123456789 0           NULL    NULL
123456789 0           NULL    NULL

这个问题Duplicated rows (x) amount of times in a table提供了一些帮助,但解决方案仍然在逃避我。

一种选择是使用递归查询:

with cte as (
    select 
        c.clientId, 
        c.numYears - (
            select count(*) from contract_reviews cr where cr.clientId = c.clientId
        ) numYears
    from contracts c
    union all
    select clientId, numYears - 1 from cte where numYears > 1
)
insert into contract_reviews(clientId) 
select clientId from cte

递归 cte 的锚计算每个客户的评论 table 中有多少行 "missing",然后递归部分生成它们。最后,外部查询执行插入。

Demo on DB Fiddle - 一旦查询执行,评论table的内容是:

ClientId  | Reviewed | YearFor | OtherColumn
:-------- | :------- | :------ | :----------
123456789 | 1        | 2018    | £100      
123456789 | 1        | 2019    | £100      
123456789 | null     | null    | null       
123456789 | null     | null    | null       
123456789 | null     | null    | null       
987654321 | null     | null    | null       
987654321 | null     | null    | null       
987654321 | null     | null    | null