각 행의 관계를 정의하기 위한 함수로 그룹 내의 연산을 쉽게 만들어준다.
Window Function 의 기본 구조
window_function(argument) over (partition by 그룹 기준 컬럼
order by 정렬 기준)
N 번째까지의 대상을 조회하고 싶을 때 (RANK)
select cuisine_type,
restaurant_name,
cnt_order,
ranking
from
(
select cuisine_type,
restaurant_name,
cnt_order,
rank() over (partition by cuisine_type order by cnt_order desc)
as ranking
from
(
select cuisine_type, restaurant_name,
count(order_id) as cnt_order
from food_orders
group by cuisine_type, restaurant_name
) as a
) as b
where ranking <= 3;
전체에서 차지하는 비율, 누적합을 구할 때 (Sum)
select restaurant_name,
cuisine_type,
cnt_order,
sum(cnt_order) over (partition by cuisine_type) as sum_cuisine,
sum(cnt_order) over (partition by cuisine_type order by cnt_order,
restaurant_name) as cum_cuisine
from
(
select restaurant_name,
cuisine_type,
count(order_id) as cnt_order
from food_orders
group by restaurant_name, cuisine_type
) as a
order by cuisine_type, cnt_order, cum_cuisine
SQL 의 연산은 숫자, 문자 외에도 날짜도 가능하다.
날짜 데이터의 이해
날짜 데이터의 여러 포맷
select date(date) as date_type,
date
from payments;
select date(date) date_type,
date_format(date(date), '%Y') "년",
date_format(date(date), '%m') "월",
date_format(date(date), '%d') "일",
date_format(date(date), '%w') "요일"
from payments;
날짜 데이터 실습
select date_format(date(date), '%Y') y,
date_format(date(date), '%m') m,
order_id
from payments;
select date_format(date(date), '%Y') as y,
date_format(date(date), '%m') as m,
count(a.order_id)
from food_orders as a inner join payments as b
on a.order_id = b.order_id
group by y, m;
select date_format(date(date), '%Y') as y,
date_format(date(date), '%m') as m,
count(a.order_id)
from food_orders as a inner join payments as b
on a.order_id = b.order_id
where date_format(date(date), '%m') = 03
group by y, m
order by y;