SQL 스터디/HackerRank

[해커랭크] MySQL CASE 구문 - Type of Triangle

황금붕어빵 2023. 9. 11. 07:16

 


 

 

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 3 sides of equal length.
  • Isosceles: It's a triangle with 2 sides of equal length.
  • Scalene: It's a triangle with 3 sides of differing lengths.
  • Not A Triangle: The given values of A, B, and C don't form a triangle.

출처 : 해커랭크

각 A, B, C 컬럼의 값을 기준으로 삼각형 유형을 출력하면 됩니다. 문제에서 삼각형 조건과 유형을 설명하고 있습니다.

 

첫 번째로는 삼각형인지 아닌지를 먼저 구분하면 됩니다.

select case
        when a+b > c and b+c > a and a+c > b then "Trianle"  
        else "Not A Triangle"
       end  
from triangles

두 개의 변이 나머지 한 변 보다 클 때 삼각형이 성립하므로 먼저 삼각형인지 아닌지 구분하고 "Not A Triangle" 조건을 완성해줍니다.

 

삼각형 조건이 성립하는 경우의 유형은 case 구문에서 then 이후에 한 번 더 case 조건을 사용하면 될 것 같습니다.

select case
        when a+b > c and b+c > a and a+c > b then 
            case
             when a = b and b = c then "Equilateral"
             when a <> b and b <> c and a <> c then "Scalene"
             else "Isosceles"
            end     
        else "Not A Triangle"
       end  
from triangles

"Equilateral" 조건은 각 변의 길이가 모두 동일할 때, "Scalene" 조건은 각 변의 길이가 모두 다를 때이므로 위와 같이 case 구문을 작성하면 됩니다.

 

 

이번 문제에서는 삼각형 조건에 대해서도 알게되었지만 중요한 것은 case 구문안에 한 번 더 case 구문을 활용할 수 있다는 점을 유의하면 될 것 같습니다.