问题:
您想要选择具有未来 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中文网其他相关文章!