根据字段值插入一行

时间:2012-06-13 17:04:46

标签: sql sql-server-2008 tsql

我的数据看起来像这样

Supplier  Qty  
--------  ---  
ABC       3
BCD       1  
CDE       2  
DEF       1  

我希望结果是:

Supplier  Qty  
--------  ---  
ABC       3   }---> Add additional row based on the number of qty
ABC       3   }
ABC       3   }
BCD       1  
CDE       2   }---> Add additional row here too
CDE       2   }
DEF       1  

寻找执行预期结果的sql SELECT语句 我正在使用Sql Server 2008

3 个答案:

答案 0 :(得分:5)

DECLARE @d TABLE (Supplier VARCHAR(32), Quantity INT);

INSERT @d SELECT 'ABC',3
UNION ALL SELECT 'BCD',1  
UNION ALL SELECT 'CDE',2  
UNION ALL SELECT 'DEF',1;

WITH x AS 
(
  SELECT TOP (10) rn = ROW_NUMBER() --since OP stated max = 10
  OVER (ORDER BY [object_id]) 
  FROM sys.all_columns 
  ORDER BY [object_id]
)
SELECT d.Supplier, d.Quantity
FROM x
CROSS JOIN @d AS d
WHERE x.rn <= d.Quantity
ORDER BY d.Supplier;

答案 1 :(得分:4)

假设您要插回到同一个表中,使用CTE来确定要插入的行干净利落。如果数量大于最大递归级别(我认为默认为100),这将工作,因此可能不是一个合适的解决方案。

;WITH SupplyToInsert (Supplier, Qty) AS (
    SELECT Supplier, Qty - 1
    FROM Supply
    WHERE Qty > 1

    UNION ALL

    SELECT S.Supplier, I.Qty - 1
    FROM Supply S
        INNER JOIN SupplyToInsert I ON I.Supplier = S.Supplier
    WHERE I.Qty > 1
)
INSERT INTO Supply (Supplier, Qty)
SELECT I.Supplier, S.Qty
FROM SupplyToInsert I
    INNER JOIN Supply S ON S.Supplier = I.Supplier

如果您不插入同一个表格,请将每个Qty > 1更改为CTE中的Qty > 0,以便为每个供应商增加一行。

工作SqlFiddle

答案 2 :(得分:2)

绝不是最漂亮的东西;并假设QTY永远不会超过10。 有更好的方法来做到这一点......但是会涉及PL \ SQL或者T-SQL无法想到直接的SQL答案。

Insert into yourTablename
(
(Select supplier, Qty From YourTableName where Qty-1 > 0) 
UNION
(Select supplier, Qty From YourTableName where Qty-2 > 0) 
UNION
(Select supplier, Qty From YourTableName where Qty-3 > 0) 
UNION
(Select supplier, Qty From YourTableName where Qty-4 > 0) 
UNION
(Select supplier, Qty From YourTableName where Qty-5 > 0) 
UNION
(Select supplier, Qty From YourTableName where Qty-6 > 0) 
UNION
(Select supplier, Qty From YourTableName where Qty-7 > 0) 
UNION
(Select supplier, Qty From YourTableName where Qty-8 > 0) 
UNION
(Select supplier, Qty From YourTableName where Qty-9 > 0) 
UNION
(Select supplier, Qty From YourTableName where Qty-10 > 0) 
)

此外,这是一次性交易;如果这不是第一次就做对了;你必须清理数据,然后再试一次。 (再次不是我最喜欢的答案,但仅限于JUST SQL ...)