By using db<>fiddle, you agree to license everything you submit by Creative Commons CC0.
CREATE TABLE mytable (
Item varchar(20),
Date date,
Quantity int,
transactionid int
);
insert into mytable values
('Part1','2023-01-01',10,3),
('Part1','2023-01-01',15,5),
('Part1','2023-01-01',17,2),
('Part1','2023-01-01',13,6),
('Part1','2023-01-02',13,7),
('Part1','2023-01-02',1,8),
('Part1','2023-01-02',22,10),
('Part1','2023-01-02',5,12);
Records: 8 Duplicates: 0 Warnings: 0
select Item, Date, min(transactionid) as opening_transaction,
max(transactionid) as closing_transaction
from mytable
group by Item, Date
Item | Date | opening_transaction | closing_transaction |
---|---|---|---|
Part1 | 2023-01-01 | 2 | 6 |
Part1 | 2023-01-02 | 7 | 12 |
select t.Item, t.Date, t.opening_transaction, op.Quantity as OpeningBal, t.closing_transaction, oc.Quantity as ClosingBal
from (
select Item, Date, min(transactionid) as opening_transaction,
max(transactionid) as closing_transaction
from mytable
group by item, Date
) t
inner join mytable op on op.transactionid = t.opening_transaction
inner join mytable oc on oc.transactionid = t.closing_transaction
Item | Date | opening_transaction | OpeningBal | closing_transaction | ClosingBal |
---|---|---|---|---|---|
Part1 | 2023-01-01 | 2 | 17 | 6 | 13 |
Part1 | 2023-01-02 | 7 | 13 | 12 | 5 |