[내일배움캠프] SQL 데이터 가공하기

김재진·2025년 11월 28일

내일배움캠프

목록 보기
5/70

1. SQL 데이터 가공하기

  • replace, substring, concat, if, case 등을 이용해서 데이터 포맷을 다르게 변경해보는 방법을 학습했다.

2. 데이터 가공을 위한 SQL 함수

  • REPLACE : REPLACE 함수는 지정한 컬럼에서 특정 문자열을 다른 문자열로 바꾸어 주는 문자열 치환 함수이다.
  • SUBPTRING : 문자열 컬럼에서 원하는 숫자 만큼 문자열을 추출하는 함수이다.
  • CONCAT : 여러 컬럼의 값을 하나로 합치는 함수이다.
  • IF : 조건문 중 하나, if(조건, 조건을 충족할 때, 조건을 충족하지 못할 때) 로 나타낸다.
  • CASE : 조건문 중 하나, if문을 여러번 사용한 효과를 낼 수 있다. case(조건1, 값1, case(조건2, 값2, 값3)) 식으로 나타낸다.

3. 실습 SQL문

다음의 값으로 배달시간이 늦었는지 판단하는 값을 만들어 보았다.

  • 주중 : 25분 이상
  • 주말 : 30분 이상
select order_id, fo.restaurant_name , day_of_the_week, fo.delivery_time ,
       case when day_of_the_week='weekday' and delivery_time>=25 then 'Late'
            when day_of_the_week='weekday' and delivery_time<25 then 'On-time'
            when day_of_the_week='weekend' and delivery_time>=30 then 'Late'
            when day_of_the_week='weekend' and delivery_time<30 then 'On-time' end "지연여부"
from food_orders fo 

내가 작성한 SQL문에는 case 함수를 4줄로 나타냈지만 Late를 결과값으로 하는 2줄을 제외한 나머지를 else를 사용하면 길이를 더 줄일 수 있는걸 나중에 알게되었다.

case when day_of_the_week='weekday' and delivery_time>=25 then 'Late'
     when day_of_the_week='weekend' and delivery_time>=30 then 'Late'
     else 'On-time' end "지연여부"

이렇게 더 짧게 작성도 가능하다

profile
개발공부 처음해보는 사람

0개의 댓글