database.sarang.net
UserID
Passwd
Database
DBMS
MySQL
ㆍPostgreSQL
Firebird
Oracle
Informix
Sybase
MS-SQL
DB2
Cache
CUBRID
LDAP
ALTIBASE
Tibero
DB 문서들
스터디
Community
공지사항
자유게시판
구인|구직
DSN 갤러리
도움주신분들
Admin
운영게시판
최근게시물
PostgreSQL Q&A 2997 게시물 읽기
No. 2997
Aggregate Function (2) -- first(), last()
작성자
정재익
작성일
2001-06-21 23:45
조회수
1,734

원본출처 : http://www.brasileiro.net/postgres/cookbook/view-one-recipe.adp?recipe_id=190

 

 

Submitted on: 04-24-2001

Description:

first() and last() aggregate functions. They're useful when writing queries that have a group by clause. Often, you're group by a key or unique ID, and including other things that rely on that ID, such as first or last name. Some database systems (such as MS Access) include first() and last() functions that return the first in a set, or the last in a set.

SELECT id, first(fname), first(lname), sum(purchaseamt)

FROM pers

GROUP BY id

 

means the same thing as

SELECT id, fname, lname, sum(purchaseamt)

FROM pers

GROUP BY id, fname, lname

 

but is often easier to understand, and easier to translate from Access. In addition, you can use these functions to force a selection from a group other than the min() or max() -- just sort the table in the order you want, then grab the first entry w/first(), or last with last().

Code:

 

-- author: joel burton (jburton@scw.org)

-- public domain

 

CREATE FUNCTION "func_first" (text,text) RETURNS text AS '

begin

if length($1) > 0 then

return $1;

else

return $2;

end if;

end;'

LANGUAGE 'plpgsql' WITH ( iscachable );

 

CREATE AGGREGATE first ( BASETYPE = text, SFUNC = func_first, STYPE = text, INITCOND = '' );

 

COMMENT ON AGGREGATE first text IS 'Return first item in aggregate';

 

COMMENT ON FUNCTION "func_first" ( text,text ) IS 'Return first item in aggregate';

 

CREATE FUNCTION "func_last" (text,text) RETURNS text AS 'begin return $2; end;' language 'plpgsql' WITH ( iscachable );

 

COMMENT ON FUNCTION "func_last" ( text,text ) IS 'Return last item in aggregate';

 

CREATE AGGREGATE last ( BASETYPE = text, SFUNC = func_last, STYPE = text, INITCOND = '' );

 

COMMENT ON AGGREGATE last text IS 'Return last item in aggregate';

[Top]
No.
제목
작성자
작성일
조회
3000Delete duplicate records in a table
정재익
2001-06-22
1910
2999Error catching
정재익
2001-06-21
1836
2998Operator --- IMP (>>> operator as logical implication)
정재익
2001-06-21
1805
2997Aggregate Function (2) -- first(), last()
정재익
2001-06-21
1734
2996Aggregate Function (1) -- comma-ify a list
정재익
2001-06-21
1868
2995Last-Change Updater
정재익
2001-06-21
1897
2994이전 시간표와 겹치지 않는지 check 하는 함수
정재익
2001-06-21
1710
Valid XHTML 1.0!
All about the DATABASE... Copyleft 1999-2024 DSN, All rights reserved.
작업시간: 0.017초, 이곳 서비스는
	PostgreSQL v16.2로 자료를 관리합니다