🐾   [MySQL] case문 사용방법

address table

id region_no
1 02
2 032
3 031
4 064

구조

select case
when 조건  then 값
when 조건  then 값
else 값
end as 명칭
from 테이블명

조건을 여러개 할때

select case
when 조건 && 조건  then 값
when 조건 || 조건 then 값
else 값
end
from 테이블명

case문 작성한 컬럼과 전체 데이터 출력하기

select case
when 조건  then 값
when 조건  then 값
else 값
end as 명칭, *
from 테이블명

케이스 문으로 만든 컬럼으로 group by 하기

select case
when 조건  then 값
when 조건  then 값
else 값
end as 명칭, count(*)
from 테이블명
group by 명칭

예시

select case
when region_no='02'  then '서울'
when region_no='031'  then '경기도'
else '기타'
end as region_name , count(*)
from address
group by region_name

​ ​ ​