본문 바로가기
Analysis & Visualization/SQL

[SQL] HackerRank - Type of Triangle

by statsbymin 2022. 8. 1.

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.

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, 23) form an Isosceles triangle, because AB.
Values in the tuple (20, 20, 20) form an Equilateral triangle, because ABC. 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.

 

문제요약

TRIANGLES 테이블에서 A, B, C컬럼은 삼각형 세 변의 길이이다. 어떤 삼각형인지 출력하라.

  • Equilateral - 모든 변의 길이가 동일한 정삼각형
  • Isosceles  - 두 변의 길이가 동일한 이등변삼각형
  • Scalene  - 세 변의 길이가 모두 다른 삼각형
  • Not A Triangle - 삼각형이 되지 못하는 경우(가장 긴 변의 길이가 나머지 두 변의 합보다 긴 경우 삼각형이 될 수 없다.)

 

풀이

MySQL

select (case 
        when A+B <= C or A+C <= B or B+C <= A then 'Not A Triangle'
        when A=B and B=C then 'Equilateral'
        when A=B or A=C or B=C then 'Isosceles'
        else 'Scalene'
             end) as red
from triangles;

CASE WHEN 문을 활용해 각 조건과 그에 맞는 결과를 설정

 

결과

 

DATA
OUTPUT