Postgres birthdays selection

后端 未结 11 1308
猫巷女王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:51

    Here's my take, which works with leap years too:

    CREATE OR REPLACE FUNCTION days_until_birthday(
        p_date date
        ) RETURNS integer AS $$
    DECLARE
        v_now date;
        v_days integer;
        v_date_upcoming date;
    
        v_years integer;
    
    BEGIN
        v_now = now()::date;
        IF (p_date IS NULL OR p_date > v_now) THEN
            RETURN NULL;
        END IF;
    
        v_years = date_part('year', v_now) - date_part('year', p_date);
    
        v_date_upcoming = p_date + v_years * interval '1 year';
    
        IF (v_date_upcoming < v_now) THEN
            v_date_upcoming = v_date_upcoming + interval '1 year';
        END IF;
    
        v_days = v_date_upcoming - v_now;
        RETURN v_days;
    END
    $$ LANGUAGE plpgsql IMMUTABLE;
    

提交回复
热议问题