Postgres birthdays selection

后端 未结 11 1304
猫巷女王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条回答
  •  一整个雨季
    2020-12-10 08:54

    Finally, to show the upcoming birthdays of the next 14 days I used this:

    SELECT 
        -- 14 days before birthday of 2000
        to_char( to_date(to_char(c.birthdate, '2000-MM-dd'), 'YYYY-MM-dd') - interval '14 days' , 'YYYY-MM-dd')  as _14b_b2000,
        -- birthday of 2000
        to_date(to_char(c.birthdate, '2000-MM-dd'), 'YYYY-MM-dd') as date_b2000,
        -- current date of 2000
        to_date(to_char(current_date, '2000-MM-dd'), 'YYYY-MM-dd') as date_c2000,
        -- 14 days after current date of 2000
        to_char( to_date(to_char(current_date, '2000-MM-dd'), 'YYYY-MM-dd') + interval '14 days' , 'YYYY-MM-dd') as _14a_c2000,
        -- 1 year after birthday of 2000
        to_char( to_date(to_char(c.birthdate, '2000-MM-dd'), 'YYYY-MM-dd') + interval '1 year' , 'YYYY-MM-dd') as _1ya_b2000
    FROM c
    WHERE 
        -- the condition 
        -- current date of 2000 between 14 days before birthday of 2000 and birthday of 2000
        to_date(to_char(current_date, '2000-MM-dd'), 'YYYY-MM-dd') between 
            to_date(to_char(c.birthdate, '2000-MM-dd'), 'YYYY-MM-dd') - interval '14 days' and 
            to_date(to_char(c.birthdate, '2000-MM-dd'), 'YYYY-MM-dd') 
        or 
        -- 1 year after birthday of 2000 between current date of 2000 and 14 days after current date of 2000
        to_date(to_char(c.birthdate, '2000-MM-dd'), 'YYYY-MM-dd') + interval '1 year' between 
            to_date(to_char(current_date, '2000-MM-dd'), 'YYYY-MM-dd') and 
            to_date(to_char(current_date, '2000-MM-dd'), 'YYYY-MM-dd') + interval '14 days' 
    ;
    

    So: To solve the leap-year issue, I set both birthdate and current date to 2000, and handle intervals only from this initial correct dates.

    To take care of the near end/beginning dates, I compared first the 2000 current date to the 2000 birthday interval, and in case current date is at the end of the year, and the birthday is at the beginning, I compared the 2001 birthday to the 2000 current date interval.

提交回复
热议问题