DB

Growing_HJ·2024년 6월 18일

일기장

목록 보기
29/51

20240618 화
조건식
case 표현식 문법

case
	when 조건 then 반환할 표현식
    when 조건 then 반환할 표현식 2
    else 반환할 표현식 3
end     

ex)

/*
 * 고객정보 조회. 활성화 고객, 비활성화 고객을 구분해서 출력.
 * customer.active : 1 : 활성화 고객(active)
 * 					 0 : 비활성화 고객(inactive)
 * */
select first_name , last_name ,
       case /* 조건식 start */
           when active = 1 then 'ACTIVE'
           else 'INACTIVE'
           end active_type  /* 조건식 end */
from customer c ;

ex2)

 -- 1. case 표현식을 사용하지 않은 경우.
/* 각각의 결과는 3행. 2번에서 1행이 되도록 해야 함.*/
select monthname(rental_date), count(*)
    from rental r
where rental_date between '2005-05-1' and '2005-08-01'
group by monthname(rental_date);

-- 2. case 표현식을 사용한 경우.
/* 1단계 : 5월, 6월, 7월에 대한 각 한건에 대한 대여정보 틀 만들기 */
    select monthname(rental_date), 1
        from rental r
    where rental_date between '2005-05-1' and '2005-08-01';

/* 2단계 5월에 대한 대여 정보만 sum 이 되도록 해보기.*/
    select
        sum((
            case when monthname(rental_date)
                          = 'MAY' then 1 else 0 end)
        )may_rental
    from rental;
-- 2단계 검증, 5월 대여 정보 row 수: 1156건.
    select count(*)
        from rental r
    where rental_date between '2005-05-1' and '2005-06-01';

/* 3단계 : 6월 7월 추가하기. */
select
    sum((
        case when monthname(rental_date) = 'MAY' then 1 else 0 end)
    )may_rental,
    sum((
        case when monthname(rental_date) = 'JUNE' then 1 else 0 end)
    )june_rental,
    sum((
        case when monthname(rental_date) = 'JULY' then 1 else 0 end)
    )july_rental
from rental;

0개의 댓글