วันอังคารที่ 24 พฤษภาคม พ.ศ. 2554

PL/PgSQL สำหรับสร้าง 'ช่วงเวลาของวัน'

นานมาแล้ว ได้เขียน PL/PgSQL สำหรับสร้าง 'ช่วงเวลาของวัน' สำหรับการวิเคราะห์ช่วงเวลาของการเกิดเหตุการณ์ โดยผู้ใช้กำหนดว่า
-6โมงเช้าถึง 7โมงเช้าเรียกว่า สล็อต1
-7โมงเช้าถึง 8โมงเช้าเรียกว่า สล็อต2
.....
และเพื่อใช้ในการ query ก็เลยเขียน PL ไว้ แต่กลัวหาย และอาจเป็นประโยชน์ ก็นำมาฝากไว้ที่นี่

ตัวอย่างการใช้งาน
FUNCTION "PS_Hour_6Slot24"(datetime timestamp with time zone, slot_number boolean)



==================== โค้ดตามนี้ครับ ===========================
-- Function: "PS_Hour_6Slot24"(timestamp with time zone, boolean)

-- DROP FUNCTION "PS_Hour_6Slot24"(timestamp with time zone, boolean);

CREATE OR REPLACE FUNCTION "PS_Hour_6Slot24"(datetime timestamp with time zone, slot_number boolean)
RETURNS text AS
$BODY$
DECLARE
hour_int integer;
hour_int_1 integer;
hour_int_2 integer;
slot_text text;
BEGIN
IF slot_number = TRUE THEN
hour_int := (to_char( datetime, 'HH24' )::integer);
hour_int := hour_int - 5;
IF hour_int < 0 THEN
hour_int := hour_int + 24;
ELSEIF hour_int = 0 THEN
hour_int := 24;
END IF;
RETURN hour_int;
ELSE
hour_int_1 := (to_char( datetime, 'HH24' )::integer);
hour_int_2 := hour_int_1 + 1;
IF hour_int_2 = 24 THEN
hour_int_2 := 0;
END IF;
slot_text := (to_char(hour_int_1, 'FM00')) || '-' || (to_char(hour_int_2, 'FM00' )) ;
RETURN slot_text;
END IF;


END;$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION "PS_Hour_6Slot24"(timestamp with time zone, boolean) OWNER TO postgres;
COMMENT ON FUNCTION "PS_Hour_6Slot24"(timestamp with time zone, boolean) IS 'return either hour-slot 1 to 24 starting from 6 o''clock or hour-slot text';
==================================================================================

ไม่มีความคิดเห็น: