未使用限定詞語法的間隔常值範例 - Amazon Redshift

Amazon Redshift 自 2025 年 11 月 1 日起不再支援建立新的 Python UDF。如果您想要使用 Python UDF,請在該日期之前建立 UDF。現有 Python UDF 將繼續正常運作。如需詳細資訊,請參閱部落格文章

未使用限定詞語法的間隔常值範例

注意

下列範例示範使用未包含 YEAR TO MONTHDAY TO SECOND 限定詞的間隔常值。如需使用包含限定詞的建議間隔常值的相關資訊,請參閱 間隔資料類型和常值

使用間隔常值來表示指定的時間期間,例如 12 hours6 months。您可以在需要表示日期時間的條件和表達式中,使用這些間隔常值。

間隔常值的表示方式,是結合 INTERVAL 關鍵字、數量和支援的日期部分,例如 INTERVAL '7 days'INTERVAL '59 minutes'。您可以串連幾個數量和單位,來組成更精確的間隔時間,例如:INTERVAL '7 days, 3 hours, 59 minutes'。也支援每種單位的縮寫和複數,例如 5 s5 second5 seconds 是相同的間隔時間。

如果未指定日期部分,則間隔值代表秒。您可以指定小數格式的數量值 (例如:0.5 days)。

下列範例顯示不同間隔值的一連串計算。

以下內容為指定日期增加 1 秒。

select caldate + interval '1 second' as dateplus from date where caldate='12-31-2008'; dateplus --------------------- 2008-12-31 00:00:01 (1 row)

以下內容為指定日期增加 1 分鐘。

select caldate + interval '1 minute' as dateplus from date where caldate='12-31-2008'; dateplus --------------------- 2008-12-31 00:01:00 (1 row)

以下內容為指定日期增加 3 個小時又 35 分鐘。

select caldate + interval '3 hours, 35 minutes' as dateplus from date where caldate='12-31-2008'; dateplus --------------------- 2008-12-31 03:35:00 (1 row)

以下內容為指定日期增加 52 週。

select caldate + interval '52 weeks' as dateplus from date where caldate='12-31-2008'; dateplus --------------------- 2009-12-30 00:00:00 (1 row)

以下內容為指定日期增加 1 週 1 小時 1 分鐘又 1 秒。

select caldate + interval '1w, 1h, 1m, 1s' as dateplus from date where caldate='12-31-2008'; dateplus --------------------- 2009-01-07 01:01:01 (1 row)

以下內容為指定指定日期增加 12 個小時 (半天)。

select caldate + interval '0.5 days' as dateplus from date where caldate='12-31-2008'; dateplus --------------------- 2008-12-31 12:00:00 (1 row)

以下內容從 2023 年 2 月 15 日減去 4 個月,結果是 2022 年 10 月 15 日。

select date '2023-02-15' - interval '4 months'; ?column? --------------------- 2022-10-15 00:00:00

以下內容從 2023 年 3 月 31 日減去 4 個月,結果是 2022 年 11 月 30 日。計算有將一個月中的天數納入考量。

select date '2023-03-31' - interval '4 months'; ?column? --------------------- 2022-11-30 00:00:00