[Oracle]Advanced 실습하기

jh5959·3일 전
0

SQL

목록 보기
8/8

NVL(형식1, 형식2)

  • NULL → 지정값으로 대체

DECODE

  • DECODE(값, 조건1, 결과1, 조건2, 결과2, ..., 기본값)

CASE

  • 복잡한 조건식 가능 (IF ~ ELSE)
  • CASE WHEN 급여 > 5000 THEN '상' ELSE '중하' END

PIVOT

  • 행 → 열 변환

ROLLUP

  • 그룹별 합계, 누계
  • GROUP BY ROLLUP(부서, 직급)

CUBE

  • 가능한 모든 그룹 조합에 대해 합계

RANK() OVER()

  • 순위 함수
  • RANK() OVER (ORDER BY 급여 DESC)

CORRELATED SUBQUERY

  • 외부쿼리와 내부쿼리가 컬럼 공유

Multi-Row 비교 연산자

  • IN, NOT IN, ANY, ALL, EXISTS, NOT EXISTS
  • ANY: 하나만 만족하면 됨
  • ALL: 전부 만족해야 됨
  • EXISTS: 조건 만족하는 값이 “존재”하면 TRUE

INDEX 사용 주의

  • 변형 ❌: SUBSTR(title, ...)
  • 부정 ❌: title <> '사원'
  • NULL ❌: 조건절에서 NULL 비교
  • OR 조건도 비추천
  • 인덱스 확인: EXPLAIN PLAN FOR ...
--nvl
select country_name,nvl(population,'0')
from country;

--decode
select name,salary,
decode(trunc(salary/1000),0,'E',1,'D',2,'C',3,'B','A') grade
from s_emp
order by salary;

--case
select country_name,
case 
when population < 50000000 then 'low'
when population >=50000000 and population < 100000000 then 'medium'
when population >=100000000 then 'high'
else '알수없음'
end as 인구등급
from country
order by 2;

--pivot
select *
from(select continent,language from country)
pivot(count(*) for language in('한국어','중국어','영어'));
--대륙별로 한국어, 중국어,영어가 공용어인 나라의 개수

--roll up
select continent,language,count(*)
from country
where language in('한국어','중국어','영어')
GROUP by rollup(continent,language)
order by continent;
--대륙별로 한국어, 중국어,영어를 공용어로 사용중인 나라의 개수와 그 나라의 총합

--rank
select country_name,population,
rank() over (order by population desc)as rank
from country
where population is not null;

--CORRELATED SubQUERY
--국가의 인구수가 그 국가가 속한 대륙의 평균 인구수보다 적은 국가에 대해 국가명,수도,대륙을 출력
select country_name,capital,continent
from country outer
where population < (select avg(population)
from country
where continent=outer.continent)
;

--Multi Row Comparison Operator
--in
--유럽(‘Europe’) 또는 아시아(‘Asia’) 대륙에 속한 국가들의 이름과 대륙을 조회하시오.
select * 
from country
where continent in('유럽','아시아')
;

--not in
--수도가 ‘서울’, ‘베이징’, ‘도쿄’가 아닌 국가의 이름과 수도를 조회하시오.
select country_name,capital
from country
where capital not in('서울','베이징','도쿄')
;

--any
--인구 수가 아시아 대륙 국가들 중 하나라도 보다 적은 국가의 이름과 인구 수를 조회하시오.
select country_name,population
from country
where population < any(select population
from country where continent='아시아')
;

--exists
select DISTINCT continent
from country
;

SELECT DISTINCT continent
FROM country c1
WHERE EXISTS (
  SELECT 1
  FROM country c2
  WHERE c2.continent = c1.continent
);

--exists
select id,name,title,dept_id
from s_emp e
where exists(select id from s_emp where manager_id=e.id)
;

--인덱스에 부정을 사용할 수 없으니 긍정에 not를 붙여서 사용
--대륙이 아시아가 아닌 나라 조회
select country_name,continent
from country c
where not exists(select 'X' from country
where c.continent='아시아')
;

0개의 댓글