반응형

RANK() 함수는 순위를 매기는 함수이다.

구문은 다음과 같다.


RANK ( ) OVER ( [ partition_by_clause ] order_by_clause )


테스트를 위해서 테이블을 생성하고 데이터를 넣는다.

create table rank_test 
(aid int,
 aname varchar(100),
 amount int)

insert into rank_test
select 1, 'aaaa', 20
union all
select 2, 'bbbb', 10
union all
select 3, 'bbbb', 10
union all
select 4, 'bbbb', 30
union all
select 5, 'cccc', 60
union all
select 6, 'cccc', 50
union all
select 7, 'dddd', 40

PARTITION BY 구문 없이 사용하면 ORDER BY 에 지정된 컬럼의 순위를 매긴다. 이때 동점의 순위는 동일하게 부여되며 그 만큼 다음 순위는 건너 띄게 된다.

select rank() over (order by amount) r, aname, amount
from rank_test


PARTITION BY 구문이 포함될 경우 PARTITION BY 에 지정된 컬럼에 대하여 그룹핑을 해서 해당 그룹 내에서 순위를 부여 하게 된다.

select rank() over (partition by aname order by amount) r, aname, amount
from rank_test


반응형

+ Recent posts