I have a test table which contains Product information and a Quantity Column.
ProdID = 1 Qty = 3
Where the Quantity is greater than 1, I need to generate the extra rows for the Quantity so output will only ever have Qty=1 against ever row:
ProdID = 1 Qty = 1
ProdID = 1 Qty = 1
ProdID = 1 Qty = 1
I'm a bit stumped where to begin, I've thought about trying to add a row then reduce Qty each time but this will be looping, how can this be done as a Set operation... recrusive cte, cross apply, can it be done in tsql?
with cte_test
as
(select a.* from
(values('01-JAN-19','PROD1','BLUE',10.00, 1)
,('01-JAN-19','PROD1','RED',10.00, 1)
,('02-JAN-19','PROD1','BLUE',10.00, 2)
,('02-JAN-19','PROD2','BLUE',10.00, 1)
,('03-JAN-19','PROD1','RED',20.00, 6)
,('04-JAN-19','PROD1','BLUE',10.00, 1)
,('04-JAN-19','PROD3','BLACK',10.00, 3)
,('05-JAN-19','PROD1','BLUE',10.00, 2)
) as a ([Date],[Product],[Colour],[Price],[Qty])
)
select [Date],[Product],[Colour],[Price],[Qty]
from cte_test
I like recursive CTEs for this purpose:
with cte as (
select [Date], [Product], [Colour], [Price], [Qty]
from [TestTable]
union all
select [Date], [Product], [Colour], [Price], [Qty] - 1
from cte
where Qty > 1
)
select [Date], [Product], [Colour], [Price], 1 as [Qty]
from cte;
If Qty
is greater than 100, you need to add option (maxrecursive 0)
.
With a recursive CTE:
declare @maxqty int = (select max(qty) from [TestTable]);
with cte AS (
select 1 qty
union all
select qty + 1 from cte where qty + 1 <= @maxqty
)
select [Date], [Product], [Colour], [Price], 1 as [Qty]
from [TestTable] t inner join cte c
on c.qty <= t.qty
order by [Date], [Product]
See the demo .
Results:
> Date | Product | Colour | Price | Qty
> :-------- | :------ | :----- | :---- | --:
> 01-JAN-19 | PROD1 | BLUE | 10.00 | 1
> 01-JAN-19 | PROD1 | RED | 10.00 | 1
> 02-JAN-19 | PROD1 | BLUE | 10.00 | 1
> 02-JAN-19 | PROD1 | BLUE | 10.00 | 1
> 02-JAN-19 | PROD2 | BLUE | 10.00 | 1
> 03-JAN-19 | PROD1 | RED | 10.00 | 1
> 03-JAN-19 | PROD1 | RED | 10.00 | 1
> 03-JAN-19 | PROD1 | RED | 10.00 | 1
> 03-JAN-19 | PROD1 | RED | 10.00 | 1
> 03-JAN-19 | PROD1 | RED | 10.00 | 1
> 03-JAN-19 | PROD1 | RED | 10.00 | 1
> 04-JAN-19 | PROD1 | BLUE | 10.00 | 1
> 04-JAN-19 | PROD3 | BLACK | 10.00 | 1
> 04-JAN-19 | PROD3 | BLACK | 10.00 | 1
> 04-JAN-19 | PROD3 | BLACK | 10.00 | 1
> 05-JAN-19 | PROD1 | BLUE | 10.00 | 1
> 05-JAN-19 | PROD1 | BLUE | 10.00 | 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.