Tuesday, May 23, 2017

SQL select advance - Type of Triangle (make use of CASE WHEN THEN ELSE END)

Problem

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:
  • Not A Triangle: The given values of A, B, and C don't form a triangle.
  • 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.
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 form an Isosceles triangle, because .
Values in the tuple form an Equilateral triangle, because . Values in the tuple form a Scalene triangle, because .
Values in the tuple cannot form a triangle because the combined value of sides and is not larger than that of side .

Answer

select
    CASE
    when(a+b>c) and (a+c>b) and (b+c>a)then
        case
            when(a=b) and (b=c) and (c=a) then 'Equilateral'
            when (a=b)or (b=c) or (a=c)then 'Isosceles'  
            else 'Scalene'
        end
    else 'Not A Triangle'
    end
from TRIANGLES

5 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. Just removed some redundance in the code, as when in the 'Equilateral' parameters you checked "when(a=b) and (b=c) and (c=a) then 'Equilateral'" the "and (c=a)" is unnecessary.

    select
    CASE
    when(a+b>c) and (a+c>b) and (b+c>a)then
    case
    when(a=b) and (b=c) then 'Equilateral'
    when (a=b)or (b=c) or (a=c)then 'Isosceles'
    else 'Scalene'
    end
    else 'Not A Triangle'
    end
    from TRIANGLES

    ReplyDelete
  4. with valid_flag as (
    select a,b,c, case
    when (a+b>c and a+c>b and b+c > a) then 1 else 0 end as valid from triangles
    ) select case
    when valid = 0 then 'Not A Triangle'
    when (a=b) and (b=c) and (a=c) then 'Equilateral'
    when (a=b) or (b=c) or (a=c) then 'Isosceles'
    else 'Scalene'
    end
    from valid_flag;

    ReplyDelete