Postgres birthdays selection

后端 未结 11 1342
猫巷女王i
猫巷女王i 2020-12-10 08:31

I work with a Postgres database. This DB has a table with users, who have a birthdate (date field). Now I want to get all users who have their birthday in the upcoming week.

11条回答
  •  猫巷女王i
    2020-12-10 08:53

    First find out how old the person currently is using age(), then grab the year from that extract(year from age()). This is how old they are currently in years, so for their age at their next birthday add 1 to the year. Then their next birthday is found by adding an interval of this many years * interval '1 year' to their birthday. Done.

    I've used a subselect here to add the next_birth_day column in to the complete table to make the select clause simpler. You can then play with the where conditions to suit your needs.

    select * 
    from (
         select *, 
           (extract(year from age(birth_date)) + 1) *  interval '1 year' + birth_date "next_birth_day"
          from public.users
    ) as users_with_upcoming_birth_days
    where next_birth_day between now() and now() + '7 days'
    

提交回复
热议问题