SQL-根据计数插入行

时间:2019-02-18 10:52:44

标签: sql sql-server recursive-query

我希望根据另一个表设置的值在表中插入许多重复的行-想法和建议将不胜感激。

tblType
Type     Qty
Apple    2
Banana   1
Mango    3

tblResult
Apple
Apple
Banana
Mango
Mango
Mango

5 个答案:

答案 0 :(得分:1)

您可以使用递归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);

答案 1 :(得分:1)

您可以使用递归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

答案 2 :(得分:0)

您可以为此尝试递归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

答案 3 :(得分:0)

您可以尝试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

答案 4 :(得分:0)

如果您不介意使用系统表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