Skip to content
Advertisement

SQL select with case when and join table

I have 2 table in sql (postgresql)

tbl1 :

dates roomid stok
2021-03-15 A01 3
2021-03-16 A01 3
2021-03-17 A01 3

tbl2 :

bookingcode startdate enddate roomid
B001 2021-03-15 2021-03-17 A01

My syntax like this

select dates, tbl1.roomid,
case
    when dates between startdate and enddate - integer '1' then stok -1
else stok
end stok
from tbl1
join tbl2
on tbl1.roomid = tbl2.roomid  order by dates asc

When the number of booking is one (tbl2), it matches results like this . The results are correct

dates roomid stok
2021-03-15 A01 2
2021-03-16 A01 2
2021-03-17 A01 3

But when the booking is 2, it’s like this (tbl2)

bookingcode startdate enddate roomid
B001 2021-03-15 2021-03-17 A01
B002 2021-03-15 2021-03-17 A01

The result is like this, the results are not suitable

dates roomid stok
2021-03-15 A01 2
2021-03-15 A01 2
2021-03-16 A01 2
2021-03-16 A01 2
2021-03-17 A01 3
2021-03-17 A01 3

The results I want when booking 2 are like this

dates roomid stok
2021-03-15 A01 1
2021-03-16 A01 1
2021-03-17 A01 3

Can anyone come up with a solution?

Advertisement

Answer

If you need to update the database just do

UPDATE tbl1 SET stok = stok - (SELECT COUNT(*) FROM tbl2 WHERE tbl1.roomid = tbl2.roomid AND tbl1.dates >= tbl2.startdate AND tbl1.dates < tbl2.enddate);

otherwise do

SELECT dates, roomid, stok - (SELECT COUNT(*) FROM tbl2 WHERE tbl1.roomid = tbl2.roomid AND tbl1.dates >= tbl2.startdate AND tbl1.dates < tbl2.enddate) FROM tbl1;
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement