简体   繁体   中英

Split a row into multiple rows based on a column value SQL

I have the following "Order Table" :

    Item        Quantity
    pencil      2
    pen         1
    Notebook    4

I need the result like :

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

You didn't specify which RDBMS you are using, so how you generate the numbers will depend on that (maybe a recursive CTE for SQL Server, using DUAL for Oracle, etc.). I've only written code to handle the data that you've shown, but you'll obviously need to account for numbers larger than four in the final solution.

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

You can use the recursive query using common table expression to generate number duplicate rows according to the quantity field as below

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM