Skip to content
Advertisement

Postgres duplicate column based on value in column

I’ve the following table in postgresql

id product customer price amount
1 Television Alfred 12.00 1
2 Radio Richard 20.00 3
3 Mobile Richard 40.00 5

Is there some way via SQL to duplicate the line n-times in case the amount is greater than one?

This is how the table should look like after running the query:

id product customer price amount
1 Television Alfred 12.00 1
2 Radio Richard 20.00 3
3 Mobile Richard 40.00 5
4 Radio Richard 20.00 3
5 Radio Richard 20.00 3
6 Mobile Richard 40.00 5
7 Mobile Richard 40.00 5
8 Mobile Richard 40.00 5
9 Mobile Richard 40.00 5

f.e. we now have 3 Radios that do match with the amount 3. Unfortunately, I do not even find a correct Google search term.

Advertisement

Answer

You can use generate_series in the group by for this:

DROP TABLE IF EXISTS _dat;

CREATE TEMP TABLE _dat 
(
  id         INT,
  product    TEXT,
  customer   TEXT,
  price      DECIMAL,
  amount     INT
);


INSERT INTO _dat (id,product,customer,price,amount) 
VALUES 
(1,'Television','Alfred',12,1),
(2,'Radio','Richard',20,3),
(3,'Mobile','Richard',40,5);

SELECT id,
       product,
       customer,
       price,
       amount
FROM _dat
GROUP BY id,
         product,
         customer,
         price,
         amount,
         GENERATE_SERIES(1,amount);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement