검색형 case의 일반적인 형태는 다음과 같다.

case
when [condition A] then resultA
when [condition B] then resultB
...
else [defaultResult]
end

when 다음으로 참 거짓이 되는 조건을 지정하고, 해당 조건이 참이면 then을 실행한다.

GroceryID Fruit Vegetable Spice Beverage Description
1 X       Apple
2 X       Orange
3     X   Mustard
4   X     Carrot
5       X Water

위와 같은 테이블이 있을 때, 검색형 case로 카테고리를 정리해볼것이다.

select
  case
    when Fruit = 'X' then 'Fruit'
    when Vegetable = 'X' then 'Vegetable'
    else 'Other'
  end as 'Category',

  [Description]

from Groceries

해당 코드는 다음과 같이 출력된다.

Category Description
Fruit Apple
Fruit Orange
Other Mustard
Vegetable Carrot
Other Water

Fruit 열이 X값을 가지고 있을 경우, category에 Fruit을, Vegetable 열이 X값을 가질경우 Vegetable을, 그 외에는 Other를 출력하게 했다.

 

'DB > 관계형 DB' 카테고리의 다른 글

WHERE절의 조건부 논리(case)  (0) 2021.04.15
Order By 조건부 논리(case)  (0) 2021.04.15
CASE  (0) 2021.04.15
패턴 매칭(Like)/ 와일드카드  (0) 2021.04.14
선택 기준 (WHERE, TOP)  (0) 2021.04.08

+ Recent posts