Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to multiply rows based on Number column in SQL

Tags:

sql

sql-server

In my case there is a delivery of Product per Area according to Nos of allotment.

Rowstamp  DocNos  ProductID  SiteCode   SiteDesc      Qty
1         AAAA    1AA        0200       Mckinley Area  2
2         AAAA    1BB        0200       Mckinley Area  3
3         AAAA    1CC        0200       Mckinley Area  1
4         BBBB    1AA        0300       Southwoods     4
5         BBBB    1BB        0300       Southwoods     2
6         BBBB    1CC        0300       Southwoods     2

But now I need a single row for each element. This will be use for tagging of box of item individually. This is the output I want:

Rowstamp  DocNos  ProductID  SiteCode   Description    Qty  
1         AAAA    1AA        0200       Mckinley Area  1
1         AAAA    1AA        0200       Mckinley Area  1
2         AAAA    1BB        0200       Mckinley Area  1
2         AAAA    1BB        0200       Mckinley Area  1
2         AAAA    1BB        0200       Mckinley Area  1
3         AAAA    1CC        0200       Mckinley Area  1
4         BBBB    1AA        0300       Southwoods     1
4         BBBB    1AA        0300       Southwoods     1
4         BBBB    1AA        0300       Southwoods     1
4         BBBB    1AA        0300       Southwoods     1
5         BBBB    1BB        0300       Southwoods     1
5         BBBB    1BB        0300       Southwoods     1
6         BBBB    1CC        0300       Southwoods     1
6         BBBB    1CC        0300       Southwoods     1

Thank You For usual support!

like image 967
Mel Zen Avatar asked Nov 14 '25 14:11

Mel Zen


1 Answers

A simple method uses a recursive subquery:

with cte as (
      select Rowstamp, DocNos, ProductID, SiteCode, Description, qty, 1 as num
      from t
      union all
      select Rowstamp, DocNos, ProductID, SiteCode, Description, qty, num + 1
      from cte
      where num <= qty
     )
select Rowstamp, DocNos, ProductID, SiteCode, Description, num as qty
from cte;
like image 118
Gordon Linoff Avatar answered Nov 17 '25 08:11

Gordon Linoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!