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