Notice
Recent Posts
Recent Comments
Link
«   2025/06   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
관리 메뉴

나의 기록

[TIL / Today I Learned] Day3 본문

개발일지/TIL

[TIL / Today I Learned] Day3

리베린 2023. 12. 21. 20:22
    • Window Function - RANK, SUM
    • Window Function 은 각 행의 관계를 정의하기 위한 함수로 그룹 내의 연산을 쉽게 만들어줍니다
    • [실습] 음식 타입별로 주문 건수가 가장 많은 상점 3개씩 조회하기

① 음식 타입별, 음식점별 주문 건수 집계하기

select cuisine_type,
restaurant_name,
count(1) cnt_order
from food_orders
group by 1,2

② Rank 함수 적용하기

select cuisine_type,
restaurant_name,
cnt_order,
rank() over (partition by cuisine_type order by cnt_order desc) ranking
from
(
select cuisine_type,
restaurant_name,
count(1) cnt_order
from food_orders
group by 1,2
) a

* rank() over (partition by cuisine_type order by cnt_order desc) ranking

우리는 음식 타입 별로 랭킹을 구할거고

우리는 주문 건수가 많을 때 1이라고 해줄거야.

 

③ 3위까지 조회하고, 음식 타입별, 순위별로 정렬하기

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) ranking
from
(
select cuisine_type,
restaurant_name,
count(1)cnt_order
from food_orders
group by 1,2
) a
) b
where ranking<=3

  • 전체에서 차지하는 비율, 누적합을 구할 때, Sum

[실습] 각 음식점의 주문건이 해당 음식 타입에서 차지하는 비율을 구하고,

          주문건이 낮은 순으로 정렬했을 때 누적 합 구하기

 

① 음식 타입별, 음식점별 주문 건수 집계하기

select cuisine_type,
restaurant_name,
count(1) cnt_order
from food_orders
group by 1,2

 

② 카테고리별 합, 카테고리별 누적합 구하기

select cuisine_type,
restaurant_name,
cnt_order,
sum(cnt_order) over (partition by cuisine_type) sum_cuisine,
sum(cnt_order) over (partition by cuisine_type order by cnt_order) cum_cuisine
from
(
select cuisine_type,
restaurant_name,
count(1) cnt_order
from food_orders
group by 1,2
) a
order by cuisine_type, cnt_order

 

 

  • date type 을 date_format 을 이용하여 년, 월, 일, 주 로 조회해보기
  1. 년 : Y (4자리), y(2자리)
  2. 월 : M, m
  3. 일 : d, e
  4. 요일 : w
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

 

date 컬럼을 date 형식으로 바꾸고,

date_format 함수를 이용해 date(date)를 %Y 년도만 남겨주겠다.

 

0 : 일요일

1: 월요일

 

 

 

음수, 양수와 상관 없이 숫자가 클수록 상관 관계가 큰 편이라고 생각하면 됩니다!

  • 양수일 경우 : 한 변수가 증가함에 따라 다른 변수도 증가하는 경향을 보이는 것
  • 음수일 경우 : 한 변수의 수치가 증가할 때 다른 변수는 감소하는 경향을 보이는 것

SQL 강의 완강 후, 파이썬 강의 시작.

파이썬 강의 끝나면

다시 SQL 강의 수강 필요..