問題:
您想要選擇具有未來14 天內的週年紀念日,但您希望通過排除年。
範例查詢:
SELECT * FROM events WHERE EXTRACT(month FROM "date") = 3 AND EXTRACT(day FROM "date") < EXTRACT(day FROM "date") + 14;
挑戰:
上述查詢不起作用,因為它不工作不工作考慮環繞效應
解決方案:
1.進階版本
此解決方案使用自訂SQL 函數和多列索引來實現最佳效能。
CREATE OR REPLACE FUNCTION f_mmdd(date) RETURNS int LANGUAGE sql IMMUTABLE PARALLEL SAFE STRICT AS 'SELECT EXTRACT(month FROM )::int * 100 + EXTRACT(day FROM )::int'; CREATE INDEX event_mmdd_event_date_idx ON event(f_mmdd(event_date), event_date); SELECT * FROM event e WHERE f_mmdd(e.event_date) BETWEEN f_mmdd(current_date) AND f_mmdd(current_date + 14);
2.表函數
此解決方案使用 PostgreSQL 表函數來處理週年紀念日計算。
CREATE OR REPLACE FUNCTION f_anniversary(_the_date date = current_date, _days int = 14) RETURNS SETOF event LANGUAGE plpgsql AS $func$ DECLARE d int := f_mmdd(); d1 int := f_mmdd( + - 1); -- fix off-by-1 from upper bound BEGIN IF d1 > d THEN RETURN QUERY SELECT * FROM event e WHERE f_mmdd(e.event_date) BETWEEN d AND d1 ORDER BY f_mmdd(e.event_date), e.event_date; ELSE -- wrap around end of year RETURN QUERY SELECT * FROM event e WHERE f_mmdd(e.event_date) >= d OR f_mmdd(e.event_date) <= d1 ORDER BY (f_mmdd(e.event_date) >= d) DESC, f_mmdd(e.event_date), event_date; -- chronological across turn of the year END IF; END $func$; SELECT * FROM f_anniversary();
以上是如何在 SQL 中計算忽略年份的日期?的詳細內容。更多資訊請關注PHP中文網其他相關文章!