PostgreSQL Count Weekend Function Example

The following function is returning the number of full weekend days between two dates.

CREATE OR REPLACE FUNCTION count_weekend_fucntion (start_date DATE, end_date DATE)
RETURNS INTEGER AS $$
DECLARE
counter INTEGER :=0;
date_counter DATE := CAST($1 as DATE);
BEGIN
LOOP
EXIT WHEN date_counter = CAST($2 as DATE);
IF (EXTRACT(DOW FROM date_counter) = 0 OR (EXTRACT(DOW FROM date_counter) = 6))
THEN counter := counter+1;
END IF;
date_counter := date_counter + INTERVAL ‘1 DAYS’;
END LOOP;
IF (EXTRACT(DOW FROM date_counter) = 0 OR (EXTRACT(DOW FROM date_counter) = 6))
THEN counter := counter+1;
END IF;
RETURN counter;
END;
$$ LANGUAGE plpgsql;

Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s