-2

I have a table T1 as below

T1

I need to copy the data from T1 to another table called T2. T2 has an additional column called 'Month' and each record from T1 needs to be copied to T2 60 times, with Month value ranging from 1 to 60.

enter image description here

I have been trying something like this and need the MONTH value to be taken dynamically , like a loop from 1 to 60. Could someone help please? Thank you

INSERT INTO T2
    SELECT PRODUCT, CUSTOMER, 1 as MONTH
    FROM T1
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Newbie
  • 713
  • 2
  • 10
  • 19
  • 3
    `CROSS JOIN` to a tally, with the values `1` to `60`. – Thom A Jul 04 '22 at 12:40
  • Does this answer your question? [How to generate a range of numbers between two numbers?](https://stackoverflow.com/questions/21425546/how-to-generate-a-range-of-numbers-between-two-numbers) – Jamiec Jul 04 '22 at 12:40
  • or https://stackoverflow.com/questions/45361887/how-can-i-create-a-temporary-numbers-table-with-sql – Jamiec Jul 04 '22 at 12:41
  • 1
    One of the key skills to learn in working with SQL is to start thinking in terms of *sets*. Not in terms of loops, procedural code, and working Row-by-agonizing-row. You want to join your `T1` with a set of the numbers 1-60. Find a way to express that (as in Tim's answer) rather than thinking of writing a loop. However, be wary also of storing computed data - is there a reason you think you need to *store* `T2` if it's actually always "the same as T1 joined with the numbers 1-60"? – Damien_The_Unbeliever Jul 04 '22 at 13:11

3 Answers3

3

We can use a cross join approach:

WITH months AS (
    SELECT n = v2.n * 10 + v1.n
    FROM (VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9)) v1(n)
    CROSS JOIN (VALUES (0), (1), (2), (3), (4), (5), (6)) v2(n)
)

INSERT INTO T2 (Product, Customer, Month)
SELECT t1.Product, t1.Customer, m.n
FROM table1 t1
CROSS JOIN months m
WHERE m.n BETWEEN 1 AND 60;
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

I used stored procedures in MySQL:

    DELIMITER $$

CREATE PROCEDURE auto_insert()
    BEGIN
        DECLARE i1 INT DEFAULT 1;
        WHILE i1 <= 60 DO
            INSERT INTO T2 SELECT *, i1 FROM T1;    
            SET i1 = i1 + 1;
        END WHILE;
    END $$
DELIMITER ;

CALL auto_insert;

Here is the result set

Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
Ozan Sen
  • 2,477
  • 2
  • 4
  • 16
0

CROSS JOIN to a tally, with the values 1 to 60. -- Thanks @Larnu for the answer.

Newbie
  • 713
  • 2
  • 10
  • 19