본문 바로가기
데이터분석 부트캠프/SQL

[데이터분석 부트캠프] SQL #4. IF, CASE, SUBQUERY

by yyezzi 2025. 9. 26.
반응형

* IF

- if(조건, 조건을 충족할 때, 조건을 충족하지 못할 때)

 

ex. 음식 타입을 ‘Korean’ 일 때는 ‘한식’, ‘Korean’ 이 아닌 경우에는 ‘기타’ 라고 지정

select restaurant_name,

           cuisine_type "원래 음식 타입",

           if(cuisine_type='Korean', '한식', '기타') "음식 타입"

from food_orders

 

* CASE

- case when 조건1 then 값(수식)1

            when 조건2 then 값(수식)2

            else 값(수식)3 end "컬럼명"

 

ex. 음식 단가를 주문 수량이 1일 때는 음식 가격, 주문 수량이 2개 이상일 때는 음식가격/주문수량 으로 지정

select order_id, price, quantity,

            case when quantity=1 then price

                     when quantity>=2 then price/quantity

             end "음식 단가"

from food_orders

 

* SUBQUERY

- select column1, special_column

   from

   ( /* subquery */

      select column1, column2 special_column

      from table1

    ) a

 

ex. 음식점의 총 주문수량과 주문 금액을 연산하고, 주문 수량을 기반으로 수수료 할인율 구하기

      (할인조건 수량이 5개 이하 → 10% 수량이 15개 초과, 총 주문금액이 300000 이상 → 0.5% 이 외에는 일괄 1%

select restaurant_name,

           case when sum_of_quantity<=5 then 0.1

                    when sum_of_quantity>15 and sum_of_price>=300000 then 0.0

                    else 0.01 end ratio_of_add

from

(

   select restaurant_name,

              sum(quantity) sum_of_quantity,

              sum(price) sum_of_price

from food_orders

group by 1

) a

반응형