根据列值SQL将行拆分为多行

时间:2016-01-06 14:07:59

标签: sql sql-server-2012

我有以下“订单表”:

    Item        Quantity
    pencil      2
    pen         1
    Notebook    4

我需要结果如:

  Item        Quantity
  pencil      1
  pencil      1
  pen         1
  Notebook    1
  Notebook    1
  Notebook    1
  Notebook    1

2 个答案:

答案 0 :(得分:1)

您没有指定您正在使用的RDBMS,因此您生成数字的方式将取决于(可能是SQL Server的递归CTE,使用DUAL for Oracle等)。我只编写代码来处理您已经显示的数据,但您显然需要在最终解决方案中考虑大于4的数字。

SELECT
    MT.sr_no,
    MT.item_name,
    1 AS quantity
FROM
    My_Table MT
INNER JOIN
    (
        SELECT 1 AS nbr UNION ALL SELECT 2 AS nbr UNION ALL
        SELECT 3 AS nbr UNION ALL SELECT 4 AS nbr
    ) N ON N.nbr <= MT.quantity

答案 1 :(得分:0)

您可以使用公共表表达式使用递归查询根据数量字段生成数字重复行,如下所示

WITH cte (sno,item,quantity,rnum)
AS
(
    SELECT sno,item,quantity, 1 as rnum
    FROM [Order]

    UNION ALL

    SELECT cte.sno,cte.item,cte.quantity, rnum+1
    FROM [Order] JOIN cte ON [Order].sno = cte.sno
    AND cte.rnum < [Order].quantity
)
SELECT item,1 AS Quantity 
FROM cte 
ORDER BY sno