P粉2538003122023-09-01 09:56:28
通常,要测试这种情况,您需要查看您感兴趣的日期是否大于入住日期并小于退房日期。例如
WHERE checkin <= '2022-12-14' and checkout >= '2022-12-14'
为了解决退房日期可以为空但仍然“OK”的情况,我们只需用满足条件的值替换空值。
SELECT * FROM my_history WHERE checkin <= '2022-12-14' and COALESCE(checkout,'2022-12-14') >= '2022-12-14'
P粉3176793422023-09-01 09:17:04
由于要求变更,已删除旧答案。匆忙之中,没有时间解释。
SELECT param.check_date, COUNT(DISTINCT p.id) FROM ( SELECT timestamp '2022-12-15 00:00' AS check_date UNION ALL SELECT timestamp '2022-12-17 00:00' AS check_date UNION ALL SELECT timestamp '2022-12-18 00:00' AS check_date ) AS param CROSS JOIN person AS p INNER JOIN my_history AS h ON h.person_id = p.id AND h.when_created >= COALESCE( ( SELECT when_created FROM my_history WHERE person_id = p.id AND when_created <= check_date ORDER BY when_created DESC LIMIT 1 ), check_date ) AND h.when_created < check_date + INTERVAL 1 DAY AND h.action = 'checked_in' GROUP BY param.check_date