설문조사
PostgreSQL/PPAS 관련 듣고 싶은 교육은


총 게시물 94건, 최근 0 건
   

DISTINCT ON (PostgreSQL 만의 고유 문법)

글쓴이 : PostgresDBA 날짜 : 2013-02-22 (금) 13:10 조회 : 19027
scott@[local]:5432:scottdb] 
SQL> create table test(x varchar(20), y int);
scott@[local]:5432:scottdb] 
SQL> insert into test values('lion',2);
INSERT 0 1
scott@[local]:5432:scottdb] 
SQL> insert into test values('lion',1);
INSERT 0 1
scott@[local]:5432:scottdb] 
SQL> insert into test values('tiger',1);
INSERT 0 1
scott@[local]:5432:scottdb] 
SQL> insert into test values('tiger',2);
INSERT 0 1
scott@[local]:5432:scottdb] 
SQL> insert into test values('rabbit',1);
INSERT 0 1
scott@[local]:5432:scottdb] 
SQL> insert into test values('rabbit',1);
INSERT 0 1
scott@[local]:5432:scottdb] 
SQL> insert into test values('rabbit',2);
INSERT 0 1
scott@[local]:5432:scottdb] 
SQL> 


SQL> select * from test;
   x    | y 
--------+---
 lion   | 2
 lion   | 1
 tiger  | 1
 tiger  | 2
 rabbit | 1
 rabbit | 1
 rabbit | 2
(7 rows)

--  아래 구문은 어느 데이터베이스에서나 볼수 있는 구문이죠. 따로 설명은 안하겠습니다.
scott@[local]:5432:scottdb] 
SQL> select distinct x, y from test order by 1,2;
   x    | y 
--------+---
 lion   | 1
 lion   | 2
 rabbit | 1
 rabbit | 2
 tiger  | 1
 tiger  | 2
(6 rows)

--  PostgreSQL 에는 distinct on 이라는 고유한 syntax 가 있습니다.
 우선 결과를 살펴볼까요?

scott@[local]:5432:scottdb] 
SQL> select distinct on(x) x as onlyOne, y from test;
 onlyone | y 
---------+---
 lion    | 1
 rabbit  | 1
 tiger   | 2
(3 rows)

scott@[local]:5432:scottdb]

x 컬럼에 대해 distinct 한 값 로우만을 가져오는 동시에,  y 컬럼까지 한번에 select 할수 있습니다.


다욱 2013-05-31 (금) 13:57
위 예제의 경우 y값이 여러개 있을 경우 어떤 값이 오는 건가요?
랜덤하게 뽑는건 아닌거 같은데 위에 있는 값이 가장 먼저 오나요?
댓글주소
PostgresDBA 2013-06-04 (화) 08:41
네 특정 순서를 원하시면 order by를 추가해야 합니다.
댓글주소
   

postgresdba.com