Re: how to sort a birthday list ?

From: Jan Wieck <JanWieck(at)Yahoo(dot)com>
To: Bruno Wolff III <bruno(at)wolff(dot)to>
Cc: Michael Agbaglo <byteshifter(at)shifted-bytes(dot)de>, josh(at)agliodbs(dot)com, pgsql-sql(at)postgresql(dot)org
Subject: Re: how to sort a birthday list ?
Date: 2002-06-21 13:22:27
Message-ID: 3D132893.8D0CBF55@Yahoo.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Bruno Wolff III wrote:
>
> On Fri, Jun 21, 2002 at 10:30:54 +0200,
> Michael Agbaglo <byteshifter(at)shifted-bytes(dot)de> wrote:
> >
> > of course you could sort by DOY but then you'll have a problem w/ the
> > next year:
> >
> > if it's let's say december and you select the list for the next 60 days,
> > persons having birthday in december will appear after persons having
> > birthday in january.
> >
> > I tried to use CASE WHEN... THEN in ORDER BY but it doesn't seem to work
> > (syntax error at '')
>
> You also need to worry about leap years. If a birthday is February 29
> and there isn't one this year, what do you want to happen?

You can create a little PL/pgSQL function like this:

CREATE FUNCTION next_birthday(date) RETURNS date AS '
DECLARE
p_dob ALIAS FOR $1;
v_age integer;
v_birthday date;
BEGIN
-- First we get the age in years
v_age := EXTRACT (YEAR FROM CURRENT_DATE) -
EXTRACT (YEAR FROM p_dob);

-- We add that to the DOB to get this years birthday
v_birthday := p_dob + (v_age::text || '' years'')::interval;

-- If that is in the past, we add another year
IF v_birthday < CURRENT_DATE THEN
v_birthday := v_birthday + ''1 year''::interval;
END IF;

RETURN v_birthday;
END;'
LANGUAGE plpgsql;

It just calculates the next birthday of a person relative from today.
Then query with

SELECT next_birthday(birthday), name
FROM person ORDER BY 1;

Jan

--

#======================================================================#
# It's easier to get forgiveness for being wrong than for being right. #
# Let's break this rule - forgive me. #
#================================================== JanWieck(at)Yahoo(dot)com #

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Dirk Lutzebaeck 2002-06-21 14:26:03 Optimizer question with equivalent joins
Previous Message Bruno Wolff III 2002-06-21 12:39:19 Re: how to sort a birthday list ?