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;
-- 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 할수 있습니다.