반응형
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 ; |
반응형
'개발 > DB' 카테고리의 다른 글
DB Index 팁 간단 정리 (ft. Maria DB, MySQL) (0) | 2022.07.07 |
---|---|
(MariaDB/mySQL) 월별 데이터 값이 가장 많은 날짜 구하기 (= 월별 데이터가 가장 많은 날) (0) | 2022.04.21 |
(Mybatis) Where 1=1 처럼 동적으로, update set 컬럼을 바꾸고 싶을때 (0) | 2022.03.22 |
(MariaDB) 범위 별로 카운트 구하기 (Group by가 아닌 범위 별 통계) (0) | 2022.01.20 |
(펌) [DBMS] [MySQL] COUNT의 잘못된 인식과 속도차이 (0) | 2022.01.18 |