Fungsi berikut mengembalikan jumlah hari akhir pekan penuh antara dua tanggal. Saat Anda membutuhkan hari penuh, Anda dapat memberikan stempel waktu ke tanggal sebelum memanggil fungsi. Ini mengembalikan 0 jika kencan pertama tidak sepenuhnya sebelum yang kedua.
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;
Contoh:
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
Untuk mendapatkan jumlah hari kecuali hari akhir pekan penuh, cukup kurangi jumlah hari dari fungsi di atas:
SELECT
'2009-04-20'::date
-
'2009-04-13'::date
-
COUNT_FULL_WEEKEND_DAYS('2009-04-13', '2009-04-20');