SELECT CASE
WHEN categoryid = 1 THEN '음료'
WHEN categoryid = 2 THEN '조미료'
ELSE '기타'
END AS 'categoryName' , *
FROM Products;
조건문으로 만든 새 칼럼으로 GROUP BY를 하고 싶다면?
SELECT CASE
WHEN categoryid = 1 THEN '음료'
WHEN categoryid = 2 THEN '소스'
ELSE '이외'
END AS newCategory
, AVG(Price)
FROM Products
GROUP BY newCategory;
HackerRank : Type of Triangle
Write a query identifying thetypeof each record in theTRIANGLEStable using its three side lengths. Output one of the following statements for each record in the table:
Equilateral: It's a triangle with 3sides of equal length.
Isosceles: It's a triangle with 2sides of equal length.
Scalene: It's a triangle with 3 sides of differing lengths.
Not A Triangle: The given values ofA,B, andCdon't form a triangle.
Input Format
TheTRIANGLEStable is described as follows:
Each row in the table denotes the lengths of each of a triangle's three sides.
Sample Input
풀이 과정
CASE에서는 WHEN 절의 순서가 중요하다!
SELECT CASE
WHEN A = B AND B = C THEN 'Equilateral'
WHEN A = B OR B = C OR A = C THEN 'Isosceles'
END AS category
FROM TRIANGLES
첫 번째 WHEN절이 A = B AND B = C로 먼저 'Equilateral'을 정의하므로
두 번째 WHEN 절에서 A = B AND B = C인 경우에도 포함되지만 위에서 먼저 'Equilateral'로 정의되었으므로 제외한다.
CASE (202040) : 두 변의 길이가 같지만 20 + 20 이 40보다 크지 않으므로 Not A Triangle이 되어야 한다.
따라서 'Isoceles'보다 'Not A Triangle'을 먼저 정의해야 한다.
SELECT CASE
WHEN A = B AND B = C THEN 'Equilateral'
WHEN A + B <= C OR A + C <= B OR B + C <= A THEN 'Not A Triangle'
WHEN A = B OR B = C OR A = C THEN 'Isosceles'
ELSE 'Scalene'
END AS category
FROM TRIANGLES