Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicating rows based on a column value in each row

Tags:

sql-server

I've this table with the following data

Job    Quantity Status Repeat
1      100      OK     2
2      400      HOLD   0
3      200      HOLD   1
4      450      OK     3

Based on the value in the Repeat column for each row, the row should be repeated again. For example for the Job 1, Repeat value is 2 so the Job 1 should repeat two more times.

The resultant table should be as below

Job    Quantity Status Repeat
1      100      OK     2
1      100      OK     2
1      100      OK     2
2      400      HOLD   0
3      200      HOLD   1
3      200      HOLD   1
4      450      OK     3
4      450      OK     3
4      450      OK     3
4      450      OK     3

Can someone please help me out with this query?

I'm using sql server

like image 403
user1345260 Avatar asked Jun 05 '12 18:06

user1345260


People also ask

Can there be duplicate rows in a table?

A table contains duplicate rows when two or more rows are identical. When you create a table, you can specify the handling of duplicate rows. By default, duplicate rows are allowed. If you disallow them, an error is generated when a user attempts to insert a duplicate row into a table.


1 Answers

This will support over 7,400 repeats for any individual job (on my system). If you need more, you can use a different system table or a cross join.

DECLARE @d TABLE (Job INT, Quantity INT, Status VARCHAR(12), Repeat INT);

INSERT @d SELECT 1, 100, 'OK'  ,2
UNION ALL SELECT 2, 400, 'HOLD',0
UNION ALL SELECT 3, 200, 'HOLD',1
UNION ALL SELECT 4, 450, 'OK'  ,3;

WITH x AS 
(
  SELECT TOP (SELECT MAX(Repeat)+1 FROM @d) rn = ROW_NUMBER() 
  OVER (ORDER BY [object_id]) 
  FROM sys.all_columns 
  ORDER BY [object_id]
)
SELECT * FROM x
CROSS JOIN @d AS d
WHERE x.rn <= d.Repeat + 1
ORDER BY Job;
like image 54
Aaron Bertrand Avatar answered Sep 20 '22 12:09

Aaron Bertrand