ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [PostgreSQL] first(), last()
    DB/PostgreSQL 2016. 11. 16. 13:54

    기타 sql에는 first()와 last() aggregate function을 제공하지만 postgresql에서는 직접 제공해주지 않습니다. 따라서 다른 sql에서 사용하는 first()와 last()를 사용하기 위해선 아래의 프로시저 함수를 추가해야 동일한 기능을 사용가능합니다.

    -- Drop a function if exists
    DROP FUNCTION IF EXISTS first_agg(anyelement, anyelement) CASCADE;
     
    -- Create a function that always returns the first non-NULL item
    CREATE OR REPLACE FUNCTION first_agg ( anyelement, anyelement )
    RETURNS anyelement LANGUAGE SQL IMMUTABLE STRICT AS $$
            SELECT $1;
    $$;
     
    -- And then wrap an aggregate around it
    CREATE AGGREGATE FIRST (
            sfunc    = first_agg,
            basetype = anyelement,
            stype    = anyelement
    );
     
    -- Drop a function if exists
    DROP FUNCTION IF EXISTS last_agg(anyelement, anyelement) CASCADE;
    -- Create a function that always returns the last non-NULL item
    CREATE OR REPLACE FUNCTION last_agg ( anyelement, anyelement )
    RETURNS anyelement LANGUAGE SQL IMMUTABLE STRICT AS $$
            SELECT $2;
    $$;
     
    -- And then wrap an aggregate around it
    CREATE AGGREGATE LAST (
            sfunc    = last_agg,
            basetype = anyelement,
            stype    = anyelement
    );


    댓글