Skip to content
Advertisement

SQL subtracting columns

I have two tables :

flight:

ID  maxcapacity
1      10 
2      12 

Flightbooking:

FlightID bookedseats 
1       2
1       3
2       2

I want to subtract booked seats from max capacity to give the number of available seats for each flight .

Expected results:

FlightID availableseats
1     5
2     10

I am new to SQL so any help would be appreciated – thanks in advance.

Advertisement

Answer

Use aggregation and join:

select f.id, f.maxcapacity - coalesce(sum(fb.bookedseats), 0) as availableseats
from flights f left join
     flightbooking fb
     on f.id = fb.flightid
group by f.id, f.maxcapacity;
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement