You can try the cte
and ROW_NUMBER()
to generate rows based on another column values as shown below.
create table tblType([Type] varchar(20), Qty int)
insert into tblType values
('Apple', 2),
('Banana', 1),
('Mango', 3)
;WITH
expanded
AS
(
SELECT [Type], Qty FROM tblType
UNION ALL
SELECT [Type], Qty - 1 FROM expanded WHERE Qty > 1
)
SELECT
*,
ROW_NUMBER() OVER (ORDER BY [Type], Qty) AS unique_ref
FROM
expanded
ORDER BY
[Type],
Qty
The output is as shown below:
Type Qty unique_ref
------------------------
Apple 1 1
Apple 2 2
Banana 1 3
Mango 1 4
Mango 2 5
Mango 3 6