본문 바로가기

┤내일배움캠프├/[ 스터디 ] SQL

SQL 5주차④(date)

728x90

date() 문자형 → 날짜형

select date,                   # 컬럼명이 date인 것
       date(date) change_date  # date()함수 적용
from payments

결과 A-Z(문자형) date에서 시계모양(날짜형) change_date가 된 것 확인 가능

 

date_format 날짜 데이터의 여러 포멧

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

결과 0은 일요일, 1은 월요일 ("년", "월" 등으로 명명해서 다시 문자형이 됨)

 

[실습] 년도별 3월 주문건수 구하기

풀이 (총 3단계)

1. 날짜형으로 데이터 가공

1-1) 날짜는 payments에, 주문건수는 food_orders에 있으므로, 공통 컬럼인 order_id를 통해 join

        from food_orders f inner join payments p on f.order_id=p.order_id

1-2) date_format()

       select date_format(date(date), '%Y') y,

                 date_format(date(date), '%m') m,

        from food_orders f inner join payments p on f.order_id=p.order_id

2. 년도, 월별 주문건수 구하기 count(1) + group by

       select date_format(date(date), '%Y'y,

                 date_format(date(date), '%m'm,

                 count(1) order_cnt

        from food_orders f inner join payments p on f.order_id=p.order_id

         group by 1,2

3. 3월 조건으로 지정, 년도별로 정렬

select date_format(date(date), '%Y') "년",
       date_format(date(date), '%m') "월",
       count(1) "주문건수"
from food_orders f inner join payments p on f.order_id=p.order_id
where date_format(date(date), '%m')='03'
group by 1,2
order by 1

결과 "년", "월" 등으로 명명해서 다시 문자형이 됨

728x90

google.com, pub-9332256070510669, DIRECT,f08c47fec0942fa0