加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

postgresql – 如何计算出生日期的下一个生日?

发布时间:2020-12-13 18:10:32 所属栏目:百科 来源:网络整理
导读:在Postgres数据库中给出此模式: CREATE TABLE person ( id serial PRIMARY KEY,name text,birth_date date,); 我如何在今天之后查询表格以获取每个人下一个生日的日期? 例如,如果Bob的birth_date是2000-06-01,那么他的下一个生日将是2016-06-01. 注意:我
在Postgres数据库中给出此模式:
CREATE TABLE person (
    id serial PRIMARY KEY,name text,birth_date date,);

我如何在今天之后查询表格以获取每个人下一个生日的日期?

例如,如果Bob的birth_date是2000-06-01,那么他的下一个生日将是2016-06-01.

注意:我不是在寻找一个预定间隔的birth_date,而是在一个人出生的下一个周年纪念日.

我在Python中编写了等价物:

def next_birthday(self):
    today = datetime.date.today()
    next_birthday = self.birth_date.replace(year=today.year)
    if next_birthday < today:
        next_birthday = next_birthday.replace(year=today.year + 1)
    return next_birthday

但是我想看看Postgres能否以更高效的方式做到这一点.

select birth_date,cast(birth_date + ((extract(year from age(birth_date)) + 1) * interval '1' year) as date) as next_birthday
from person
where name = 'Bob'

表达式(提取物(年龄(birth_date))1)*间隔“1”年计算(完整)年份下一个生日的年龄.将其添加到出生日期时,这将给下一个生日.

由于日期间隔返回时间戳(包括时间),因此需要使用强制转换才能获得真实的日期.

如果你删除where条件,你将获得所有“下一个”生日.

您还可以获取即将到来的生日列表,例如:接下来的30天使用这样的东西:

select next_birthday,next_birthday - current_date as days_until_next
from (
  select birth_date,cast(birth_date + ((extract(year from age(birth_date)) + 1) * interval '1' year) as date) as next_birthday
  from person
) as upcoming
where upcoming.next_birthday <= current_date + 30
order by next_birthday;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读