HackerRank-My SQL

Prepare > SQL > Advanced Select > Type of Triangle

stem_sw 2023. 7. 15. 12:15
 

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.

 

 

 

 

코드


SELECT 
CASE
    WHEN A+B > C AND B+C > A AND C+A > B THEN 
        (CASE WHEN A=B AND B=C THEN 'Equilateral'
            WHEN A=B OR B=C OR C=A THEN 'Isosceles'
            ELSE 'Scalene' END)
    ELSE 'Not A Triangle' END

FROM TRIANGLES;

 

 

 

 

노트


항 비교연산은 두 개씩만 할 수 있음

A+B > C AND B+C > A AND C+A > B
A=B AND B=C
A=B OR B=C OR C=A
  • A = B = C같은거 안됨

 

 

CASE WHEN ~ THEN ~ END는 중첩 가능

 

두 번째 시도

SELECT IF((A >= B+C) or (B >= A+C) or (C >= A+B), 'Not A Triangle',
    CASE
        WHEN A=B AND B=C THEN 'Equilateral'
        WHEN A=B OR C=B OR C=A THEN 'Isosceles'
        ELSE 'Scalene' END
)
FROM TRIANGLES;
  • IF(조건, 참일 경우, 거짓일 경우)
  • 조건을 차례로 필터링