简体   繁体   English

PostgreSQL:如何检查日期字段是否与今天匹配?

[英]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. 问题是,如果记录是在一个月的29日,30日或31日创建的,则电子邮件可能不会发送出去。 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: 这是一个SQL调用,该调用将在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 如果是这样,请检查创建的日期是否与该日期匹配或在该日期之后,否则请检查其是否完全匹配

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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