SQL

CASE (+ 해커랭크 예제)

얆생 2024. 10. 12. 00:47
  • CASE

python의 if문처럼 경우에 따른 조건을 걸어줄 때 사용

 

기본 코드

SELECT CASE
           WHEN 칼럼명 = '특정 값' THEN '출력할 값'
           WHEN 칼럼명2 = '특정 값2' THEN '출력할 값2'
           ELSE '출력할 값3'
       END
FROM 테이블명

 

 

1. Products 테이블에서 CategoryID가 1인 데이터는 '음료', 2인 데이터는 '조미료', 나머지는 '기타'로 표시해라.

SELECT CASE
           WHEN categoryid = 1 then '음료'
           WHEN categoryid = 2 then '조미료'
           ELSE '기타'
       END AS 'CategoryName', *
FROM Products

 

>> 이렇게 조건 걸어주면 각 값들이 대응하여 출력되고, END로 끝내면 된다.

     출력이 잘 된건지 확인을 해주려면 *(아스타)도 같이 출력, 다른 데이터도 같이 볼 수 있다.

 

 

 

2. WHEN절에 두 가지 조건 같이 쓰는 경우

SELECT CASE
           WHEN categoryid = 1 AND Supplierid = 1 then '음료'
           WHEN categoryid = 2 then '조미료'
           ELSE '기타'
       END, *
FROM Products

 

 

 

3. CASE에서 새로 만든 칼럼을 기준으로 GROUP BY하기

 

categoryid별로 대응값을 지정해서 새 칼럼을 만들고, 그걸 기준으로 평균 가격 출

SELECT CASE
           WHEN categoryid = 1 then '음료'
           WHEN categoryid = 2 then '소스'
           ELSE '이외'
       END AS new_category
       , AVG(Price)
GROUP BY new_category
FROM Products

 

 

 

 

  • 해커랭크 예제 풀이

https://www.hackerrank.com/challenges/what-type-of-triangle/problem?isFullScreen=true

 

Type of Triangle | HackerRank

Query a triangle's type based on its side lengths.

www.hackerrank.com

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.

Input Format

The TRIANGLES table is described as follows:

Each row in the table denotes the lengths of each of a triangle's three sides.

Sample Input

Sample Output

Isosceles
Equilateral
Scalene
Not A Triangle

Explanation

Values in the tuple (20, 20, 30)  form an Isosceles triangle, because A ≡ B.
Values in the tuple (20, 20, 20)  form an Equilateral triangle, because A ≡ B C. Values in the tuple (20, 21, 22)  form a Scalene triangle, because A ≠ B C .
Values in the tuple (13, 14, 30) cannot form a triangle because the combined value of sides A and B is not larger than that of side C.

 

 

문제 해석

A,B,C는 각 변의 길이

세 변으로 만들 수 있는 삼각형 중에 정삼각형, 이등변 삼각형, 일반 삼각형, 삼각형 안되는거 4가지가 있음

각 데이터마다 어떤 모양인지 대응해서 출력해라

 

 

풀이 접근

1. 무조건 정삼각형 되는 경우, A = B = C >> 근데 이렇게 쓰면 안되고 A = B and B = C가 맞음

2. 삼각형이 안 만들어지는 경우, ex) A + B <= C, B + C <= A, A + C <= B >> or로 묶기

3. 1,2번 제외한 것들 중에 이등변 되는 경우, A = B, B = C, A = C >> or로 묶기

   3-1. 3번을 제외한 모든 경우, 일반 삼각형이 됨

4. 위를 토대로 case문 작성

 

CASE에 여러 개의 WHEN절을 쓸 때는, 조건이 적용될 순서가 중요하다

>> 이 문제에서 정삼각형도 이등변 삼각형에 속하기 때문에, 확실한 A = B = C인 경우는 정삼각형으로 대응시켜주기 위함

 

잘 대응되는지 확인하기 위해 select에 A, B, C포함해서 결과 확인하기

 

최종 코드

SELECT CASE
           WHEN A = B AND B = C THEN 'Equilateral'
           WHEN A + B <= C OR A + C <= B OR B + C <= A THEN 'Not A Triangle'
           WHEN A = B OR B = C OR A = C THEN 'Isosceles'
           ELSE 'Scalene'
       END
FROM TRIANGLES