[Database] row number

row number


row_number는 번호를 매기는 건데 over(order by 컬럼값) 을 넣어 설정할 수 있다.

select row_number() over(order by qty desc) "주문량"
    , procure_request_no
    , qty
    from procure_procure_request
    where procure_request_date between '20170103' and '20170110';

예를 들어 위 sql문은 row_number를 추가하고 qty, 주문량이 많은 순서대로 정렬하도록 설정했다. 그러면 데이터들이 qty가 많은 순서대로 정렬되어 조회된다.

그림1

desc를 asc로 바꿔서 주문량이 적은 순서대로 조회할 수 있다. 또한 order by에 기준이 되는 컬럼을 여러개 추가할 수 있다.

select row_number() over(order by qty desc, procure_request_no asc) "주문량"
       ,procure_request_no
       , qty
from procure_procure_request
where procure_request_date between '20170103' and '20170110';

그러면 같은 값의 qty 주문량 데이터중 procure_request_no가 낮은 순으로 정렬된다.
또한 partition by 컬럼을 추가하여 컬럼 같은 값을 묶음으로 하여 그 묶음 안에서 정렬을 할 수 있다.

select row_number() over(partition by procure_request_date order by qty desc, procure_request_no asc) "주문량"
       , procure_request_date
       ,procure_request_no
       , qty
from procure_procure_request
where procure_request_date between '20170103' and '20170110';

위 sql문은 partition by procure_request_date를 지정하여 procure_request_date를 기준으로 같은 값을 소그룹을 만들어 그 안에서 qty, 주문량이 높은 순으로, 그리고 주문량이 같으면 procure_request_no가 낮은 순으로 정렬하도록 지시하고 있다. 그 결과 데이터는 아래 그림처럼 조회된다.

그림2

이 기능은 어렵지만 오라클의 필수 기능이므로 꼭 숙지하도록 해야한다.






© 2021.11. by 21thkafka

Powered by 21thkafka