반응형

Case문이란?

쿼리에서 If / Switch문의 역할

= 조건을 이용한 결과값 출력

 

사용 방법

  • CASE문은 조건을 통과 첫번째 조건이 충족되면 값을 반환
  • 조건이 true : 결과 반환,
    조건이 false : else 값을 반환
  • Else문이 없으면 null 반환
  • When - then 항상 같이 사용하며, 여러 set 사용가능

 

예제

특정 기간 동안의 원하는 날짜를 가져오는 쿼리

= 검색 기준으로부터 해당월, 1달전, 2달전, 3달전, 4달전, 12달전, 13달전의 결제일(=해당월의 가장큰 read_dt) 검색

= case when read_dt 202203이면 read_dt 출력하되, 'read_dt'라는 이름으로 출력
 case when read_dt 202202이면 read_dt 출력하되, 'oneMonthAgo'라는 이름으로 출력

= 하나의 컬럼을 여러 개의 컬럼(=하나의 로우)으로 출력 가능

 

 

    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


select
        max(bill_dt.readDt) readDt,
        max(bill_dt.oneMonthAgo) oneMonthAgo,
        max(bill_dt.twoMonthAgo) twoMonthAgo,
        max(bill_dt.threeMonthAgo) threeMonthAgo,
        max(bill_dt.fourMonthAgo) fourMonthAgo,
        max(bill_dt.twelveMonthAgo) twelveMonthAgo,
        max(bill_dt.thirteenMonthAgo) thirteenMonthAgo
from (
        select
                case
                        when substring(READ_DT,1,6) = '202203' then READ_DT
                end as 'readDt',
                case
                        when substring(READ_DT,1,6) = '202202' then READ_DT
                end as 'oneMonthAgo',
                case
                        when substring(READ_DT,1,6) = '202201' then READ_DT
                end as 'twoMonthAgo',
                case
                        when substring(READ_DT,1,6) = '202112' then READ_DT
                end as 'threeMonthAgo',
                case
                        when substring(READ_DT,1,6) = '202111' then READ_DT
                end as 'fourMonthAgo',
                case
                        when substring(READ_DT,1,6) = '202103' then READ_DT
                end as 'twelveMonthAgo',
                case
                        when substring(READ_DT,1,6) = '202102' then READ_DT
                end as 'thirteenMonthAgo'
        from gnd_meter_billing gmb
        where READ_DT between 20210301000000 and 20220322000000
group by substring(READ_DT,1,6), substring(READ_DT,7,2)
) bill_dt
;
반응형

+ Recent posts