declare @booking table
(
id int identity,
busid int,
scheduleid int,
stopnumber smallint,
stopnumber2 smallint,
seatscount smallint
);
insert into @booking(busid, scheduleid, stopnumber, stopnumber2, seatscount)
values
(1, 6, null, null, 2),
(1, 6, null, 1, 2),
(1, 6, null, 2, 1),
(1, 6, null, 3, 2),
(1, 6, 1, null, 2),
(1, 6, 1, 2, 1),
(1, 6, 1, 3, 1),
(1, 6, 2, null, 1),
(1, 6, 2, 3, 1),
(1, 6, 3, null, 2);
select * from @booking;
select *,
--total number of passengers that got on the bus at previous¤t stops
(select isnull(sum(e.seatscount), 0) from @booking as e where e.busid = b.busid and e.scheduleid = b.scheduleid and isnull(e.stopnumber, 0) <= isnull(b.stopnumber, 0))
-
--total number of passengers that got off the bus at previous¤t stops
(select isnull(sum(d.seatscount), 0) from @booking as d where d.busid = b.busid and d.scheduleid = b.scheduleid and d.stopnumber2 <= b.stopnumber)
as PassengersOnBusAtStopNumber
from @booking as b;