Re: counting days

From: SCassidy(at)overlandstorage(dot)com
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 22:44:50
Message-ID: OFD00DF88C.FA6249F2-ON882571D9.007C2EDE-882571D9.007CF46E@overlandstorage.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

If I understood you correctly, you want the number of weekdays (e.g. an
integer number of days) between 2 specified dates.

This seems to work (although I am not the greatest plpgsql function person
- not enough practice - there may be better ways):

CREATE or REPLACE FUNCTION count_weekdays (date, date) returns integer
language plpgsql STABLE
AS '
DECLARE
start_date alias for $1;
end_date alias for $2;
tmp_date date;
tmp_dow integer;
-- double precision returned from extract
tot_dow integer;
BEGIN
tmp_date := start_date;
tot_dow := 0;
WHILE (tmp_date <= end_date) LOOP
select into tmp_dow cast(extract(dow from tmp_date) as integer);
IF ((tmp_dow >= 2) and (tmp_dow <= 6)) THEN
tot_dow := (tot_dow + 1);
END IF;
select into tmp_date (tmp_date + interval ''1 day '');
END LOOP;
return tot_dow;

END;
';

select count_weekdays(date '2006-08-01', date '2006-08-10');
count_weekdays
----------------
8
(1 row)

Note that I used 2 single-quotes around ''1 day'', not double quotes. I'm
on version 7.4.6.

Susan Cassidy


garry saddington
<garry(at)schoolteac
hers.co.uk> To
Sent by: pgsql-general(at)postgresql(dot)org
pgsql-general-own cc
er(at)postgresql(dot)org
Subject
[GENERAL] counting days
08/29/2006 11:35
AM
|-------------------|
| [ ] Expand Groups |
|-------------------|





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.
Regards
Garry

---------------------------(end of broadcast)---------------------------
TIP 6: explain analyze is your friend

----------------------------------------------------------------------------------------------
Simply protected storage solutions ensure that your information is
automatically safe, readily available and always there, visit us at http://www.overlandstorage.com
----------------------------------------------------------------------------------------------

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Ron Johnson 2006-08-29 22:48:35 Re: strange sum behaviour
Previous Message CSN 2006-08-29 22:03:08 Re: database files are incompatible with server, after computer restart