SQL - 根据计数插入行

SQL - Insert rows based on count

我希望根据其他人设置的值将多个重复行插入 table - 非常感谢您的想法和建议。

tblType
Type     Qty
Apple    2
Banana   1
Mango    3

tblResult
Apple
Apple
Banana
Mango
Mango
Mango

你可以使用递归 cte :

with cte as (
   select t.type, t.qty, 1 as start
   from table t
   union all
   select c.type, c.qty, start + 1 
   from cte c
   where start < c.qty
)

insert into table (type)
     select c.type
     from cte c
     order by c.type
     option (maxrecusrion 0);

您可以使用递归 CTE 构建数据:

WITH rcte AS (
    SELECT Type, Qty, 1 AS n
    FROM tbltype
    WHERE Qty > 0

    UNION ALL

    SELECT Type, Qty, n + 1
    FROM rcte
    WHERE n < Qty
)

-- INSERT INTO tblresult
SELECT Type
FROM rcte

您可以为此尝试递归 CTE

DECLARE @T TABLE
(
    SeqNo INT IDENTITY(1,1),
    [Type] VARCHAR(20),
    Qty INT
)

INSERT INTO @T
VALUES('Apple',2),('Banana',1),('Mango',3)

;WITH CTE
AS
(
    SELECT
        [Type],
        Qty
        FROM @T
    UNION ALL
    SELECT
        [Type],
        Qty = Qty -1
        FROM CTE
            WHERE Qty>1
)
SELECT
    *
    FROM CTE
    ORDER BY [Type]

结果

Type                 Qty
-------------------- -----------
Apple                2
Apple                1
Banana               1
Mango                3
Mango                2
Mango                1

您可以尝试 cteROW_NUMBER() 根据另一列值生成行,如下所示。

create table tblType([Type] varchar(20), Qty int)
insert into tblType values
('Apple',    2),
('Banana',   1),
('Mango',   3)

;WITH
  expanded
AS
(
  SELECT [Type], Qty FROM tblType    
  UNION ALL    
  SELECT [Type], Qty - 1 FROM expanded WHERE Qty > 1
)

SELECT
  *,
  ROW_NUMBER() OVER (ORDER BY [Type], Qty) AS unique_ref
FROM
  expanded
ORDER BY
  [Type],
  Qty

输出如下图:

Type    Qty    unique_ref
------------------------
Apple    1     1
Apple    2     2
Banana   1     3
Mango    1     4
Mango    2     5
Mango    3     6

如果您不介意使用系统 table master..[spt_values] 并且您的 Qty 不能超过 2537,那么您可以使用以下查询。

它会比递归更快 CTE

SELECT t1.type 
FROM   tbltype t1 
       INNER JOIN (SELECT ( Row_number() 
                              OVER (ORDER BY (SELECT NULL)) ) RN 
                   FROM   master..[spt_values] T1) t2 
               ON t1.qty >= t2.rn