2

I have an order table and I will keep it simple. I need to split the rows based on the quantity in the order. For example, if an order quantity is 4 I need to split the original rows into 4 rows with quantity of 1 each. Example data below.

ID     FKID     Product     QTY
1      100      Widget      4

I need a result like this.

 ID     FKID     Product     QTY
 1       100      Widget      1
 2       100      Widget      1
 3       100      Widget      1
 4       100      Widget      1
1
  • HOw high could QTY go? Commented Mar 25, 2021 at 19:45

2 Answers 2

5

Just another option using an ad-hoc tally table and a simple JOIN

Example

Select ID = row_number() over (partition by A.ID order by N)
      ,FKID
      ,Product
      ,Qty = 1
 From  YourTable A
 Join (
        Select Top (1000) N=Row_Number() Over (Order By (Select NULL)) 
         From  master..spt_values n1 ,master..spt_values n2 
      ) B on N<=A.[QTY]

Returns

ID  FKID    Product Qty
1   100     Widget  1
2   100     Widget  1
3   100     Widget  1
4   100     Widget  1
Sign up to request clarification or add additional context in comments.

Comments

-1

One simple method is a recursive CTE:

with cte as (
      select  ID, FKID, Product, QTY
      from t
      union all
      select  ID, FKID, Product, QTY - 1
      from t
      where qty > 1
     )
select id, fkid, product, 1 as qty
from cte;

The only caveat is that if qty can be 100 or greater, you'll need option (maxrecursion 0).

2 Comments

Note that if you are going to have much higher numbers, an rCTE is going to be far slower, that a non-iterative method. If it's going to be <=10, or even 100, and the data sets small, the difference will be negligible.
I think this will do it. I establish the base column and then split X times as I need. Not sure if the quantity will exceed 100. I will have to look at the production data. But I don't think it will go that high. Thanks!

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.