[SQL] 조건문(CASE)

간략 정리

CASE

Id Color
1 Red
2 Blue
Null Unspecified
1
2
3
4
5
6
7
SELECT Id
     , CASE Id
            WHEN 1 THEN Red
            WHEN 2 THEN Blue
            ELSE Unspecified
       END AS Color
FROM table1;
  • ELSE를 생략할 경우에는 ELSE NULL이 자동으로 지정 WHEN절의 조건에 아무것도 부합하지 않은 데이터가 있는 경우 ELSE 절에 값을 지정해주지 않으면 해당 값은 자동으로 NULL값을 반환한다.

TABLE PIVOT

categoryid price
1 3
1 4
2 70
2 60
1
2
3
4
5
6
7
8
9
SELECT AVG(CASE
               WHEN categoryid = 1 THEN price
               ELSE NULL
           END) AS category1_avg_price
     , AVG(CASE
               WHEN categoryid = 2 THEN price
               ELSE NULL
           END) AS category2_avg_price
FROM sample;
category1_avg_price category2_avg_price
3.5 65
  • 세로로 표시되는 테이블 결과물을 가로로 보고싶을 때 사용하는 쿼리이다.
  • CASE문을 이용하여 각각의 컬럼에 맞는 데이터만 출력하고 나머지는 null 값을 가지도록 하여, 각 컬럼에서 보고싶은 연산(COUNT, SUM, AVG 등등)의 결과를 보여준다.

해커랭크 문제풀이

Type of Triangle

  • 문제 바로가기

  • 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.

풀이

1
2
3
4
5
6
7
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 C = A THEN 'Isosceles' -- 이등변 삼각형
            ELSE 'Scalene'
       END
FROM TRIANGLES;

리트코드 문제풀이

1179. Reformat Department Table

1
2
3
4
5
6
7
8
9
10
+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| id          | int     |
| revenue     | int     |
| month       | varchar |
+-------------+---------+
(id, month) is the primary key of this table.
The table has information about the revenue of each department per month.
The month has values in ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].
  • Write an SQL query to reformat the table such that there is a department id column and a revenue column for each month.
  • Return the result table in any order.
  • The query result format is in the following example.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Input: 
Department table:
+------+---------+-------+
| id   | revenue | month |
+------+---------+-------+
| 1    | 8000    | Jan   |
| 2    | 9000    | Jan   |
| 3    | 10000   | Feb   |
| 1    | 7000    | Feb   |
| 1    | 6000    | Mar   |
+------+---------+-------+
Output: 
+------+-------------+-------------+-------------+-----+-------------+
| id   | Jan_Revenue | Feb_Revenue | Mar_Revenue | ... | Dec_Revenue |
+------+-------------+-------------+-------------+-----+-------------+
| 1    | 8000        | 7000        | 6000        | ... | null        |
| 2    | 9000        | null        | null        | ... | null        |
| 3    | null        | 10000       | null        | ... | null        |
+------+-------------+-------------+-------------+-----+-------------+
Explanation: The revenue from Apr to Dec is null.
Note that the result table has 13 columns (1 for the department id + 12 for the months).

풀이

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
SELECT id
     , SUM(CASE
            WHEN month = 'Jan' THEN revenue
       END) AS 'Jan_Revenue'
     , SUM(CASE
            WHEN month = 'Feb' THEN revenue
       END) AS 'Feb_Revenue'
     , SUM(CASE
            WHEN month = 'Mar' THEN revenue
       END) AS 'Mar_Revenue'
     , SUM(CASE
            WHEN month = 'Apr' THEN revenue
       END) AS 'Apr_Revenue'
     , SUM(CASE
            WHEN month = 'May' THEN revenue
       END) AS 'May_Revenue'
     , SUM(CASE
            WHEN month = 'Jun' THEN revenue
       END) AS 'Jun_Revenue'
     , SUM(CASE
            WHEN month = 'Jul' THEN revenue
       END) AS 'Jul_Revenue'
     , SUM(CASE
            WHEN month = 'Aug' THEN revenue
       END) AS 'Aug_Revenue'
     , SUM(CASE
            WHEN month = 'Sep' THEN revenue
       END) AS 'Sep_Revenue'
     , SUM(CASE
            WHEN month = 'Oct' THEN revenue
       END) AS 'Oct_Revenue'
     , SUM(CASE
            WHEN month = 'Nov' THEN revenue
       END) AS 'Nov_Revenue'
     , SUM(CASE
            WHEN month = 'Dec' THEN revenue
       END) AS 'Dec_Revenue'
FROM Department
GROUP BY id
  • case문에서 sum을 빠뜨렸었다.
  • sum 함수의 사용 이유에 대해 araboza.
  • Pivot 확실히 이해하기: Pivoting Data in SQL
    • id를 세 가지만 표시하기 위해서, group by를 사용해줬는데 집계를 해주지 않으면, 나머지 값들이 무시되기 때문이다!
0%