How do you do date math that ignores the year?

前端 未结 8 1697
梦谈多话
梦谈多话 2020-11-28 11:14

I am trying to select dates that have an anniversary in the next 14 days. How can I select based on dates excluding the year? I have tried something like the following.

8条回答
  •  悲&欢浪女
    2020-11-28 12:08

    You can generate a virtual table of anniversaries, and select from it.

    with anniversaries as (
      select event_date, 
             (event_date + (n || ' years')::interval)::date anniversary
      from events, generate_series(1,10) n
    )
    select event_date, anniversary
    from anniversaries
    where anniversary between current_date and current_date + interval '14' day
    order by event_date, anniversary
    

    The call to generate_series(1,10) has the effect of generating 10 years of anniversaries for each event_date. I wouldn't use the literal value 10 in production. Instead, I'd either calculate the right number of years to use in a subquery, or I'd use a large literal like 100.

    You'll want to adjust the WHERE clause to fit your application.

    If you have a performance problem with the virtual table (when you have a lot of rows in "events"), replace the common table expression with a base table having the identical structure. Storing anniversaries in a base table makes their values obvious (especially for, say, Feb 29 anniversaries), and queries on such a table can use an index. Querying an anniversary table of half a million rows using just the SELECT statement above takes 25ms on my desktop.

提交回复
热议问题