I'm stuck and in need of some help please. I am using SQL 2017.
How can I repeat the below data based on field WC_Count but also increase op number as well?
As-is
Job | StockCode | Warehouse | Op | Op_Count | WC_Count |
---|---|---|---|---|---|
000000000219587 | CODE1 | 1W | 1 | 6 | 4 |
000000000219587 | CODE2 | 1W | 2 | 6 | 4 |
000000000219587 | CODE3 | 1W | 3 | 6 | 4 |
000000000219587 | CODE4 | 1W | 4 | 6 | 4 |
000000000219587 | CODE5 | 1W | 5 | 6 | 4 |
000000000219587 | CODE6 | 1W | 6 | 6 | 4 |
To be
Job | StockCode | Warehouse | Op | Op_Count | WC_Count |
---|---|---|---|---|---|
000000000219587 | CODE1 | 1W | 1 | 6 | 4 |
000000000219587 | CODE2 | 1W | 2 | 6 | 4 |
000000000219587 | CODE3 | 1W | 3 | 6 | 4 |
000000000219587 | CODE4 | 1W | 4 | 6 | 4 |
000000000219587 | CODE5 | 1W | 5 | 6 | 4 |
000000000219587 | CODE6 | 1W | 6 | 6 | 4 |
000000000219587 | CODE1 | 1W | 7 | 6 | 4 |
000000000219587 | CODE2 | 1W | 8 | 6 | 4 |
000000000219587 | CODE3 | 1W | 9 | 6 | 4 |
000000000219587 | CODE4 | 1W | 10 | 6 | 4 |
000000000219587 | CODE5 | 1W | 11 | 6 | 4 |
000000000219587 | CODE6 | 1W | 12 | 6 | 4 |
000000000219587 | CODE1 | 1W | 13 | 6 | 4 |
000000000219587 | CODE2 | 1W | 14 | 6 | 4 |
000000000219587 | CODE3 | 1W | 15 | 6 | 4 |
000000000219587 | CODE4 | 1W | 16 | 6 | 4 |
000000000219587 | CODE5 | 1W | 17 | 6 | 4 |
000000000219587 | CODE6 | 1W | 18 | 6 | 4 |
000000000219587 | CODE1 | 1W | 19 | 6 | 4 |
000000000219587 | CODE2 | 1W | 20 | 6 | 4 |
000000000219587 | CODE3 | 1W | 21 | 6 | 4 |
000000000219587 | CODE4 | 1W | 22 | 6 | 4 |
000000000219587 | CODE5 | 1W | 23 | 6 | 4 |
000000000219587 | CODE6 | 1W | 24 | 6 | 4 |
You can use a recursive subquery. You don't describe the exact logic for incrementing op
, so I'll just use row_number()
:
with cte as (
select Job, StockCode, Warehouse, Op, Op_Count, WC_Count, 1 as n
from t
union all
select Job, StockCode, Warehouse, Op, Op_Count, WC_Count, n + 1
from cte
where n < wc_count
)
select Job, StockCode, Warehouse,
row_number() over (order by n, op) as op,
op_count, wc_count
from cte;
Here is a db<>fiddle.