关于酒店预订系统还有其他帖子,我有一些好主意。但是,我坚持使用SQL查询。我想要的是出售房间的查询结果。每天需要有一排,每天每种房型都有一个房间出售的数量。例如,它看起来会这样,但是缺少room_types为0:
我已经能够创建一个查询,该查询将生成一系列日期,然后计算每个日期销售的房间。如果没有任何room_type出售房间,则在剩余字段中提供带有NULL的日期行。这是查询:
SELECT the_date::date, bookings.room_type, COUNT(bookings.id) as booked
FROM generate_series('2018-04-04'::date, '2019-04-04'::date, interval '1 day') the_date
LEFT JOIN (SELECT arrival_date, id, departure_date, room_type
FROM bookings
WHERE cancelled IS NULL
AND checked_out IS NULL)
bookings
ON the_date BETWEEN bookings.arrival_date AND (bookings.departure_date - INTERVAL '1 DAY')
GROUP BY the_date, bookings.room_type
ORDER BY the_date, bookings.room_type
我的问题是,即使特定房型没有任何预订,我也需要显示所有房型。它应该在预订列中显示房间类型为0。我有一个room_types表,其中room_type是主键,预订中的room_type采用外键。我尝试加入room_types表但是我的数据不正确。
预订表如下所示:
Room_types表如下所示:
答案 0 :(得分:1)
您可以像这样使用CROSS JOIN
SELECT the_date::date, rt.room_type, COUNT(bookings.id) as booked
FROM generate_series('2018-04-04'::date, '2019-04-04'::date, interval '1 day') the_date
CROSS JOIN room_types rt
LEFT JOIN (SELECT arrival_date, id, departure_date, room_type
FROM bookings
WHERE cancelled IS NULL
AND checked_out IS NULL)
bookings
ON the_date BETWEEN bookings.arrival_date AND (bookings.departure_date - INTERVAL '1 DAY') and
bookings.room_type = rt.room_type
GROUP BY the_date, rt.room_type
ORDER BY the_date, rt.room_type