얼마 전 공모전을 준비하던 중 데이터를 특정 유저에 대해 그 내부적으로 log의 sequence로 정렬해야 했던 경험을 했다. 당시에 python의 pandas dataframe을 변형시키며 구현을 시도했는데, SQL의 window function을 사용할 경우 더 효과적으로 짧은 쿼리로도 결과를 조회 가능하여 이를 정리해보고자 한다.
Aggregate Function : COUNT, SUM, MIN, MAX, AVG, ... etc
Aggregate function의 경우 주로 결과가 하나의 row로 보여짐. 예를 들어 특정 Table 내의 Column 값들의 총합 (SUM)을 SELECT문으로 조회할 경우 집계함수를 사용한 결과가 합계값 하나로만 나타남.
A window function performs a calculation across a set of table rows that are somehow related to the current row. This is comparable to the type of calculation that can be done with an aggregate function. But unlike regular aggregate functions, use of a window function does not cause rows to become grouped into a single output row — the rows retain their separate identities. Behind the scenes, the window function is able to access more than just the current row of the query result.
- postgresql document
window function의 경우 주로 window frame으로 인식되는 단위에서 동작함.
sum(cost) over ( partition by customer_id)
예를 들어 Aggregate function이 특정 partition by Dep_name 에 대해 연산될 경우, Dep_name에서 나눈 partition내의 모든 row가 window frame으로 인식됨.
sum(cost) over ( partition by customer_id order by cost)
뒤에 order by가 추가로 사용되는 경우, order by한 column의 각각의 row 모두가 window frame으로 인식되어 모든 row에 대해 aggregate function(위의 경우 sum)을 적용한 결과가 리턴된다.
with
table_01 as (
select order_id, customer_id, order_date
, lag(order_date) over (partition by customer_id order by order_date) as prev_ord_date
from orders
)
select * from table_01;
(Array의 경우 조회 결과 또는 결과 내 특정 집합을 의미)
만약 위의 출력 결과 중에서 [NULL] 부분을 출력하고 싶지 않은 경우,
where prev_order_date is not null
의 조건문을 추가해주면 된다.