次の関数は、2つの日付の間の完全な週末の日数を返します。丸一日が必要なため、関数を呼び出す前にタイムスタンプを日付にキャストできます。最初の日付が厳密に2番目の日付より前でない場合は、0を返します。
CREATE FUNCTION count_full_weekend_days(date, date)
RETURNS int AS
$BODY$
SELECT
($1 < $2)::int
*
(
(($2 - $1) / 7) * 2
+
(EXTRACT(dow FROM $1)<6 AND EXTRACT(dow FROM $2)>0 AND EXTRACT(dow FROM $1)>EXTRACT(dow FROM $2))::int * 2
+
(EXTRACT(dow FROM $1)=6 AND EXTRACT(dow FROM $2)>0)::int
+
(EXTRACT(dow FROM $2)=0 AND EXTRACT(dow FROM $1)<6)::int
);
$BODY$
LANGUAGE 'SQL' IMMUTABLE STRICT;
例:
SELECT COUNT_FULL_WEEKEND_DAYS('2009-04-10', '2009-04-20');
# returns 4
SELECT COUNT_FULL_WEEKEND_DAYS('2009-04-11', '2009-04-20');
# returns 3 (11th is Saturday, so it shouldn't be counted as full day)
SELECT COUNT_FULL_WEEKEND_DAYS('2009-04-12', '2009-04-20');
# returns 2 (12th is Sunday, so it shouldn't be counted as full day)
SELECT COUNT_FULL_WEEKEND_DAYS('2009-04-13', '2009-04-20');
# returns 2
週末全体を除く日数を取得するには、上記の関数から日数を引くだけです。
SELECT
'2009-04-20'::date
-
'2009-04-13'::date
-
COUNT_FULL_WEEKEND_DAYS('2009-04-13', '2009-04-20');