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
Views: Raw Message | Whole Thread | Download mbox | Resend email
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

Browse pgsql-general by date

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