DECLARE @Products TABLE (
ORDERNO INT, RefNO int, Size int, quantity int)
INSERT INTO @Products(ORDERNO, RefNO, Size, quantity)
VALUES ( 26, 1, 7,20),(26, 2, 7,10),(27,4, 8,40)
;with mycte as (
SELECT a.ORDERNO,a.RefNO,a.Size,a.quantity, (
SELECT SUM(b.quantity)
FROM @Products b WHERE a.ORDERNO=b.ORDERNO
AND b.RefNO <= a.RefNO) AS runningTotal
,row_number() over(partition by ORDERNO order by RefNO ) rn
FROM @Products AS a
)
Select m1.ORDERNO,m1.RefNO,m1.Size,m1.quantity,
Case when m1.rn=1 then '01-'+Cast(m1.quantity as varchar(10))
else Cast(m2.runningTotal+1 as varchar(10))+'-'+Cast(m1.runningTotal+1 as varchar(10)) end NoOfQuantity
from mycte m1
left join mycte m2 on m1.ORDERNO=m2.ORDERNO
and m1.rn=m2.rn+1
ORDER BY m1.ORDERNO,m1.RefNO;
/*
ORDERNO RefNO Size quantity NoOfQuantity
26 1 7 20 01-20
26 2 7 10 21-31
27 4 8 40 01-40
*/