8

One of my tables in my database contains rows with requisition numbers and other related info. I am trying to create a second table (populated with an INSERT INTO statement) that duplicates these rows and adds a series value based on the value in the QuantityOrdered column.

For example, the first table is shown below:

+-------------+----------+
| Requisition | Quantity |
+-------------+----------+
| 10001_01_AD |    4     |
+-------------+----------+

and I would like the output to be as follows:

+-------------+----------+----------+
| Requisition | Quantity |  Series  |
+-------------+----------+----------+
| 10001_01_AD |     4    |     1    |
| 10001_01_AD |     4    |     2    |
| 10001_01_AD |     4    |     3    |
| 10001_01_AD |     4    |     4    |
+-------------+----------+----------+

I've been attempting to use Row_Number() to sequence the values but it's numbering rows based on instances of Requisition values, not based on the Quantity value.

Michael Bruesch
  • 632
  • 7
  • 23
Steven F
  • 95
  • 1
  • 6

3 Answers3

5

You need recursive way :

with t as (
     select Requisition, 1 as start, Quantity
     from table
     union all
     select Requisition, start + 1, Quantity
     from t
     where start < Quantity
 ) 
select Requisition, Quantity, start as Series  
from t; 

However, by default it has limited to only 100 Quantities, if you have a more then you need to specify the query hint by using option (maxrecursion 0).

Yogesh Sharma
  • 49,870
  • 5
  • 26
  • 52
5

Non-recursive way:

SELECT *
FROM tab t
CROSS APPLY (SELECT n
             FROM (SELECT ROW_NUMBER() OVER(ORDER BY 1/0) AS n
                   FROM master..spt_values s1) AS sub
             WHERE  sub.n <= t.Quantity) AS s2(Series);

db<>fiddle demo

Lukasz Szozda
  • 162,964
  • 23
  • 234
  • 275
2

A simple method uses recursive CTEs:

with cte as (
      select requsition, quantity, 1 as series
      from t
      union all
      select requsition, quantity, 1 + series
      from t
      where lev < quantity
    )
select requsition, quantity, series
from cte;

With default setting, this works up to a quantity of 100. For larger quantities, you can add option (maxrecursion 0) to the query.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786