코딩짜는 머글 2024. 9. 9. 22:50

 

사용할 수 없는 데이터가 있거나, 값이 없는 경우에는 null문법을 이용해준다.

 

*다른 값을 대체해서 사용하고 싶을때*

다른 값이 있을 때 조건문 이용하기 : if(rating>=1, rating, 대체값)

null 값일 때 : coalesce(age, 대체값)

 

pivot table

 

pivot table : 2개 이상의 기준으로 데이터를 집계할 때, 보기 쉽게 배열하여 보여주는 것을 의미

 


pivot view 구조 만들기

 

select restaurant_name,
       max(if(hh='15', cnt_order, 0)) "15",
       max(if(hh='16', cnt_order, 0)) "16",
       max(if(hh='17', cnt_order, 0)) "17",
       max(if(hh='18', cnt_order, 0)) "18",
       max(if(hh='19', cnt_order, 0)) "19",
       max(if(hh='20', cnt_order, 0)) "20"
from 
(
select a.restaurant_name,
       substring(b.time, 1, 2) hh,
       count(1) cnt_order
from food_orders a inner join payments b on a.order_id=b.order_id
where substring(b.time, 1, 2) between 15 and 20
group by 1, 2
) a
group by 1
order by 7 desc

 


window function

 각 행의 관계를 정의하기 위한 함수로 그룹 내의 연산을 쉽게 만들어준다.

 

window function 의 기본 구조

window_function(argument) over (partition by 그룹 기준 컬럼 order by 정렬 기준)

 

window_function : 기능 명을 사용함(sum, avg와 같이 기능명이 있음)

argument : 함수에 따라 작성하거나 생략함.

partition by : 그룹을 나누기 위한 기준. group by 절과 유사하다고 생각하면 됨.

order by : window function 을 적용할 때 정렬 할 컬럼 기준을 적어줌


rank

특정 기준으로 순위를 매겨주는 기능

rank 는 기본적으로 argument  부분을 비워서 사용한다. (기본 구조는 동일)

 

yyyy-mm-dd 형식의 컬럼을 date type 으로 변경하는 법

 

select date(date) date_type,
       date
from payments

 

date type 을 date_format 을 이용하여 년, 월, 일, 주 로 조회하는법

년 : Y (4자리), y(2자리)

월 : M, m

일 : d, e

요일 : 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


 

문제를 풀다가 새로 알게된 것***

 

LIMIT 절은 반환할 레코드 수를 지정하는 데 사용된다.

LIMIT 절은 수천 개의 레코드가 있는 대규모 테이블에 유용하다.  많은 수의 레코드를 반환하면 성능에 영향을 미칠 수 있다.

limil 기본 구문

 

SELECT column_name

FROM table_name

WHERE condition

LIIMIT number;