CASE

 

SQL에서도 CASE문을 이용해 조건문을 작성할 수 있다.

CASE의 작성 방법을 파악하기 위한 예시를 하나 들어보자.

 

ex)

SELECT CASE WHEN shipperid = 1 THEN 'A'
            WHEN shipperid = 2 THEN 'B'
            ELSE 'C'
       END AS Shipper, *
FROM Orders

  • shipperid가 1일 경우 A, shipperid가 2일 경우 B, 나머지는 C
  • AS를 이용해 조건문의 결과값의 별칭을 Shipper라고 지정
  • *를 이용해 전체 테이블을 Shipper 컬럼과 함께 출력
  • CASE문은 반드시 END로 닫아줘야 함

 

CASE는 GROUP BY와 함께 사용할 수도 있다.

ex)

SELECT CASE WHEN shipperid = 1 THEN 'A'
            WHEN shipperid = 2 THEN 'B'
            ELSE 'C'
       END AS Shipper, count(orderid) AS orders_num
FROM Orders
GROUP BY shipper

  • shipper를 기준으로 그룹화하여 orderid의 개수를 출력
  • GROUP BY의 기준인 shipper는 반드시 SELECT문에 적어줘야 함

 

 

 

 

<HackerRank 문제풀이>

 

Type of Triangle

▶ Write a query identifying the type of each record in the TRIANGLES table using its three side lengths. Output one of the following statements for each record in the table:

  • Equilateral: It's a triangle with  sides of equal length.
  • Isosceles: It's a triangle with  sides of equal length.
  • Scalene: It's a triangle with  sides of differing lengths.
  • Not A Triangle: The given values of A, B, and C don't form a triangle.  
Column Type
A Integer
B Integer
C Integer

 

Idea)

  1. CASE 조건문 이용하기
  2. Triangle과 Not A Triangle로 구분하기
  3. Triangle 중 Isosceles, Scalene, Scalene로 구분하기
SELECT CASE
            WHEN a >= b + c OR b >= a + c OR c >= a + b THEN 'Not A Triangle'
            WHEN a = b AND b = c THEN 'Equilateral'
            WHEN a = b OR b = c OR c = a THEN 'Isosceles'
            ELSE 'Scalene'
        END
FROM triangles

* CASE 조건문은 위에서 아래로 순서대로 진행되므로 순서 배치에 유의해야 한다.

  만약, Isosceles를 구별하는 문장을 Equilateral을 구별하는 문장의 앞에 배치하면 a=b=c인 삼각형은

  Equilateral이 아니라 Isosceles로 구분된다.

 

 

 

 


 

 

↘↘↘

[백문이불여일타] 데이터 분석을 위한 중급 SQL

https://www.inflearn.com/course/%EB%8D%B0%EC%9D%B4%ED%84%B0-%EB%B6%84%EC%84%9D-%EC%A4%91%EA%B8%89-sql

'📖 STUDY > SQL' 카테고리의 다른 글

[SQL] INNER JOIN, LEFT JOIN, RIGHT JOIN, SELF JOIN  (0) 2022.03.15
[SQL] CASE_테이블 피봇  (0) 2022.03.08
[SQL] GROUP BY, HAVING  (0) 2022.03.08
[SQL] COUNT, SUM, AVG, MIN, MAX  (0) 2022.03.07
[SQL] review_HackerRank  (0) 2022.03.04

+ Recent posts