INTERVAL 運算
如果你在經營一家真正的 DVD 出租店,有時需要判斷目前有哪些片名還在顧客手上。在上一題中,我們看到查詢結果裡有些紀錄的 return_date 是 NULL。這表示該筆租賃尚未歸還。
film 資料表中的每筆租賃都有一個對應的 rental_duration 欄位,代表顧客在被視為逾期之前能租借 DVD 的天數。在這個練習中,你會排除 return_date 為 NULL 的片子,並且把 rental_duration 轉換為 INTERVAL 型別。以下是進行此轉換的一種作法提醒:
SELECT INTERVAL '1' day * timestamp '2019-04-10 12:34:56'
本練習屬於課程
在 PostgreSQL 操作資料的函式
練習說明
- 以 1 天的
INTERVAL乘上rental_duration,將其轉換。 - 用
return_date減去rental_date,計算days_rented的天數。 - 排除
return_date為NULL的租賃紀錄。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
SELECT
f.title,
-- Convert the rental_duration to an interval
___ '1' ___ * ___.___,
-- Calculate the days rented as we did previously
r.return_date - ___.___ AS days_rented
FROM film AS f
INNER JOIN inventory AS i ON f.film_id = i.film_id
INNER JOIN rental AS r ON i.inventory_id = r.inventory_id
-- Filter the query to exclude outstanding rentals
WHERE r.return_date ___ ___ ___
ORDER BY f.title;