Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a row on 2 or more rows depending on a column

I have a question If I have one row that looks like this

|ordernumber|qty|articlenumber|
|  123125213| 3 |fffff111     |

How can I split this into three rows like this:

|ordernumber|qty|articlenumber|
|  123125213| 1 |fffff111     |
|  123125213| 1 |fffff111     |
|  123125213| 1 |fffff111     |

/J

like image 894
secret_cinema Avatar asked Jul 10 '13 12:07

secret_cinema


1 Answers

You can use recursive CTE:

WITH RCTE AS 
(
    SELECT  
        ordernumber, qty, articlenumber, qty AS L
    FROM Table1

    UNION ALL

    SELECT      
        ordernumber, 1, articlenumber, L - 1 AS L
    FROM RCTE
    WHERE L>0
)
SELECT  ordernumber,qty, articlenumber
FROM RCTE WHERE qty = 1

SQLFiddleDEMO

EDIT: Based on Marek Grzenkowicz's answer and MatBailie's comment, whole new idea:

WITH CTE_Nums AS 
(
    SELECT MAX(qty) n FROM dbo.Table1
    UNION ALL
    SELECT n-1 FROM CTE_Nums
    WHERE n>1  
)
SELECT  ordernumber ,
        1 AS qty,
        articlenumber
FROM dbo.Table1 t1
INNER JOIN CTE_Nums n ON t1.qty >= n.n

Generating number from 1 to max(qty) and join table on it.

SQLFiddle DEMO

like image 144
Nenad Zivkovic Avatar answered Sep 22 '22 21:09

Nenad Zivkovic