Description
Table: Triangle
| Column Name | Type |
|---|---|
| x | int |
| y | int |
| z | int |
- In SQL,
(x, y, z)is the primary key column for this table. - Each row of this table contains the lengths of three line segments.
Problem Statement
Report for every three line segments whether they can form a triangle. Return the result table in any order.
The result format is in the following example.
Example 1:
Input:
Triangletable:
| x | y | z |
|---|---|---|
| 13 | 15 | 30 |
| 10 | 20 | 15 |
Output:
| x | y | z | triangle |
|---|---|---|---|
| 13 | 15 | 30 | No |
| 10 | 20 | 15 | Yes |
For three sides to be able to create a triangle, the sum of any two sides must be greater than the third side of the
triangle. That is x + y > z condition must be satisfied for each sides.
That is, it should hold true all three conditions below.
1x + y > z
2y + z > x
3z + x > y
Solution
In this case, we need to derive new column triangle which contains Yes or No based on whether the three sides specified in x, y and z can form a triangle. You can verify whether they can form a triangle by ensuring that the sum of two sides is greater than the third side for all possible combinations.
To assign the value of Yes or No to the new column, we can use a CASE WHEN statement.
1SELECT x, y, z,
2 CASE
3 WHEN x + y > z AND y + z > x AND z + x > y THEN 'Yes'
4 ELSE 'No'
5 END AS triangle
6 FROM Triangle;


Comments