By using db<>fiddle, you agree to license everything you submit by Creative Commons CC0.
CREATE TABLE t
(refrn int, code int, qty int, amount int)
;
INSERT INTO t
(refrn, code, qty, amount)
VALUES
(1000, 000, 0, 50),
(1000, 112, 10, 500),
(1000, 631, 10, 25),
(2000, 000, 0, 40),
(2000, 345, 10, 600),
(2000, 631, 10, 25)
;
6 rows affected
select refrn
,code
,sum(qty) as qty
,sum(amount) as amount
from (
select refrn
,case code when 0 then lead(code) over(partition by refrn order by code) else code end as code
,qty
,amount
from t
) t
group by refrn, code
order by refrn
refrn | code | qty | amount |
---|---|---|---|
1000 | 112 | 10 | 550 |
1000 | 631 | 10 | 25 |
2000 | 345 | 10 | 640 |
2000 | 631 | 10 | 25 |