Skip site navigation (1) Skip section navigation (2)

Re: counting days

From: David Fetter <david(at)fetter(dot)org>
To: garry saddington <garry(at)schoolteachers(dot)co(dot)uk>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: counting days
Date: 2006-08-29 23:40:43
Message-ID: 20060829234043.GM6923@fetter.org (view raw or flat)
Thread:
Lists: pgsql-general
On Tue, Aug 29, 2006 at 07:35:27PM +0100, garry saddington wrote:
> I need to count the days between two dates that are not saturdays or
> sundays.  I have read the manual and searched the lists but I am
> struggling.  I can count the days but am finding difficulty
> excluding sat and sun from the count.  I need this without reference
> to any tables.  Does anyone have any pointers please.

You can do this with an SQL function.  The function below includes
both the start date and end date, but you could adjust it so that it
takes either or neither.  You can query it as though it were a table,
e.g.

SELECT * FROM non_weekends_between('2006-08-01'::date, 'today'::date);

or in your case,

SELECT COUNT(*) FROM non_weekends_between('2006-08-01'::date, 'today'::date);

Regards,
David.

CREATE OR REPLACE FUNCTION non_weekends_between(
    first_date DATE, /* $1 */
    last_date DATE   /* $2 */
)
RETURNS SETOF date
LANGUAGE sql
AS
$$
SELECT
    $1 + s.i
FROM generate_series(
    0,
    $2 - $1
) AS s(i)
WHERE
    extract(
        DOW
    FROM
        $1 + s.i
    ) NOT IN (
        0,  /* Sunday   */
        6   /* Saturday */
    );
$$;
-- 
David Fetter <david(at)fetter(dot)org> http://fetter.org/
phone: +1 415 235 3778        AIM: dfetter666
                              Skype: davidfetter

Remember to vote!

In response to

pgsql-general by date

Next:From: RagnarDate: 2006-08-29 23:46:35
Subject: Re: counting days
Previous:From: CSNDate: 2006-08-29 23:23:48
Subject: Re: database files are incompatible with server, after computer restart

Privacy Policy | About PostgreSQL
Copyright © 1996-2014 The PostgreSQL Global Development Group