SQL/MySQL 문제풀이

Type of Triangle(HackerRank)

관재탑 2022. 7. 18. 19:58

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.

 

 

정답쿼리

SELECT  CASE 
WHEN A + B <= C OR B + C <= A OR B + C <= A 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
FROM TRIANGLES

 

해설

CASE문에서는 순서가 중요하다. 위에서 내려오면서 차례대로 조건이 적용되기 때문이다. 

NOT A Triangle이 맨 위에 있어야 한다. 예를 들어 Isosceles의 조건을 만족하면서 동시에 'NOT A Triangle'의 조건도 만족가능하기 때문에 Isosceles가 NOT A Triangle위에 있으면 NOT A Triangle이 되어야 할 데이터가 Isosceles가 되기 때문이다.