Home > Database > Mysql Tutorial > How to Calculate Dates Ignoring the Year in SQL?

How to Calculate Dates Ignoring the Year in SQL?

DDD
Release: 2025-01-05 07:48:40
Original
141 people have browsed it

How to Calculate Dates Ignoring the Year in SQL?

How to perform date calculations that ignore the year using SQL

Problem:

You want to select dates that have an anniversary within the next 14 days, but you want to do this by excluding the year.

Example Query:

SELECT *
FROM events
WHERE EXTRACT(month FROM "date") = 3
AND EXTRACT(day FROM "date") < EXTRACT(day FROM "date") + 14;
Copy after login

Challenge:

The above query doesn't work because it doesn't account for the wrap-around effect of months.

Solutions:

1. Advanced Version

This solution uses a custom SQL function and a multicolumn index for optimal performance.

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);
Copy after login

2. Table Function

This solution uses a PostgreSQL table function to handle the anniversary calculation.

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();
Copy after login

The above is the detailed content of How to Calculate Dates Ignoring the Year in SQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template