본문 바로가기
일일 문제 풀이/HackerRank

[SQL] 해커랭크 HackerRank 문제 풀이 Type of Triangle - Advanced Select

by 엘리는 코딩 마스터 2025. 3. 11.

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.

 

Explanation

Values in the tuple (20, 20, 23) 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.

 

 

정답

select case when A+B<=C or B+C<=A or A+C<=B then 'Not A Triangle'
            when A=B and B=C then 'Equilateral'
            when A=B or B=C or A=C then 'Isosceles'
            else 'Scalene' end triangle_type
from TRIANGLES;

 

배운 점

  1. 삼각형을 만들려면 두변의 합이 나머지 한변의 합보다 커야 한다(A+B>C)
  2. SQL은 A=B=C 이렇게 조건을 세개 거는 거는 안된다 그래서 A=B and B=C 이렇게 진행해야 한다.
    1. 처음에는 A=B=C 이렇게 했는데 안되어서 확인해보니 그렇다
  3. case when 구문도 python의 if문 처럼 위에서 부터 순차적으로 걸러지는 형태이다. 그래서 어떤 조건을 먼저 걸지가 중요하다.