KDT/DB

240321 DB - 조건부 표현식 2

001cloudid 2024. 3. 21. 13:00
728x90

조건부 표현식

decode 함수

case 식과 같은 문법. = 연산자를 내포하고 있음

decode(컬럼|표현식, 찾는 내용1, 결과1[,찾는 내용 2, 결과 2,...][,기본값])

 

select last_name, job_id, salary,
decode(job_id, 'IT_PROG, 1.1*salary,
				'ST_CLERK', 1.15*salary,
                'SA_REP', 1.2*salary,
                salary) REVISE_SALARY
from employees;

 

※ 객체를 혼자 쓰일 수 있는 것이라고 생각한다면 테이블, 뷰, 인덱스, 시퀀스, 시노님, 함수 등이 객체라고 할 수 있다.

※ case식과 decode 함수를 비교하면 case식이 더 성능이 좋음. decode함수는 객체이기 때문이다.

 

그림 1. decode함수 예시 2


연습문제

-- 1
SELECT JOB_ID,
CASE JOB_ID WHEN 'AD_PRES' THEN 'A'
			WHEN 'ST_MAN' THEN 'B'
            WHEN 'IT_PROG' THEN 'C'
            WHEN 'SA_REP' THEN 'D'
            WHEN 'ST_CLERK' THEN 'E'
            ELSE '0' END "GRADE"
FROM EMPLOYEES;

-- ==
SELECT JOB_ID,
DECODE(JOB_ID, 'AD_PRES','A',
				'ST_MAN','B',
                'IT_PROG','C',
                'SA_RPE','D',
                'ST_CLERK','E',
                '0') GRADE
FROM EMPLOYEES;

 

-- 2
select count(employee_id) total,
sum(case when hire_date between '02/01/01' and '02/12/31' then count(employee_id) end) "2002",
sum(case when hire_date between '03/01/01' and '03/12/31' then count(employee_id) end) "2003",
sum(case when hire_date between '04/01/01' and '04/12/31' then count(employee_id) end) "2004",
sum(case when hire_date between '05/01/01' and '05/12/31' then count(employee_id) end) "2005"
from employees
group by hire_date
having hire_date between '02/01/01' and '05/12/31';

 

-- 3
select job_id "Job"
sum(case when department_id = 20 then salary end) "Dept20",
sum(case when department_id = 50 then salary end) "Dept50",
sum(case when department_id = 80 then salary end) "Dept80",
sum(case when department_id = 90 then salary end) "Dept90",
sum(salary) "Total"
from employees
group by job_id;

 

 

728x90