简体   繁体   中英

PostgreSQL: How to check if day in date field matches today?

I would like to send out an email every month on the same day that a record was created. The issue is that if the record was created on the 29th, 30th, or 31st day of a month, then the email may not get sent out. How can I check if the day field matches today, or otherwise, if that day does not exist for the current month, then check if today is the last day of the month?

For reference, here is a example table:

CREATE TABLE charges (
  id INTEGER,
  dt_created TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
)

And here is a SQL call that would work for days 1-28:

SELECT id FROM charges WHERE extract(day from dt_created) = extract(day from now())

The naive implementation for that could look like:

with dt as (select '2014-03-31'::date dt_created, '2014-02-28'::date now)

select
case when extract(day from (date_trunc('MONTH', now) + INTERVAL '1 MONTH - 1 day')) = extract(day from now)
then extract(day from dt_created) >= extract(day from now)
else extract(day from dt_created) = extract(day from now)
end matches
from dt

So you first check if the current day is the last day in this month. If so - check if created day matches the day or is later, otherwise check if it simply matches

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM