[英]Insert unique value multiple times depending on variable column
我的表中有以下列:
PromotionID | NumberOfCodes
1 10
2 5
我需要多次将PromotionID
插入到新的 SQL 表中 - 取决于NumberOfCodes
的值。
因此,鉴于上述情况,我的结果集应为:
PromotionID
1
1
1
1
1
1
1
1
1
1
2
2
2
2
2
你需要递归 cte :
with r_cte as (
select t.PromotionID, 1 as start, NumberOfCodes
from table t
union all
select id, start + 1, NumberOfCodes
from r_cte
where start < NumberOfCodes
)
insert into table (PromotionID)
select PromotionID
from r_cte
order by PromotionID;
默认递归级别 100,如果您有更多 NumberOfCodes,请使用查询提示option(maxrecursion 0)
。
我更喜欢对这些事情进行统计。 一旦您开始使用更大的行集,rCTe 的性能就会迅速下降:
WITH N AS(
SELECT N
FROM (VALUES(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL))N(N)),
Tally AS(
SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS I
FROM N N1, N N2) --Up to 100 rows. Add more cross joins to N for more rows
SELECT YT.PromotionID
FROM dbo.YourTable YT
JOIN Tally T ON YT.NumberOfCodes >= T.I;
一种选择使用递归公用表表达式从源表生成行,然后您可以将其插入到目标表中:
with cte as (
select promotion_id, number_of_codes n from sourcetable
union all select promotion_id, n - 1 from mytable where n > 1
)
insert into targettable (promotion_id)
select promotion_id from cte
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.