0

I want to insert rows base on cell value in Column QuantityTable in Producttemp table and insert into table ProductionActual For example, the first table is shown below:

Table Producttemp

+-------------+----------+
| Requisition | Quantity |
+-------------+----------+
| GJ002_01_AD |    5     |
| GJ002_02_AD |    3     |
+-------------+----------+

and I would like the output to be as follows:

Table Productactual

+-------------+----------+----------+
| Requisition | Quantity |  Series  |
+-------------+----------+----------+
| GJ002_01_AD |     5    |     1    |
| GJ002_01_AD |     5    |     2    |
| GJ002_01_AD |     5    |     3    |
| GJ002_01_AD |     5    |     4    |
| GJ002_01_AD |     5    |     5    |
| GJ002_02_AD |     3    |     1    |
| GJ002_02_AD |     3    |     2    |
| GJ002_02_AD |     3    |     3    |

I found similar question below for sql server, but it's not working in MySQL database

Generating Rows Based on Column Value

2
  • There are 3 answers in the published link - which of them did you try that didn't work? also add the mysql version you are on.. Commented Dec 12, 2022 at 8:50
  • Does this answer your question? CROSS/OUTER APPLY in MySQL Commented Dec 12, 2022 at 8:53

1 Answer 1

1

Try this, this will create new rows with running numbers in series

`

WITH RECURSIVE 
Factor (Requisition, Quantity, Series, FactorKey) AS
(
    SELECT Requisition, Quantity,1,CONCAT(Requisition, Quantity,) FROM Producttemp
    UNION ALL
    SELECT 
        Requisition, 
        Quantity,
        IF(FactorKey != CONCAT(Requisition, Quantity),2,Series+1) AS Series ,
        CONCAT(Requisition, Quantity)
    FROM 
        Quantity WHERE Series<Quantity 
    
)
SELECT * FROM Factor ORDER BY Requisition, Quantity;

`

Sign up to request clarification or add additional context in comments.

2 Comments

the recursive query will disappear after refreshing the table. is there a way to put them into another table after your query? or any suggestions?
I think you can create a stored procedure, declare a cursor that reads the source table, and for each row inserts qty rows into the destination table.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.