뇨내

[Oracle - SQL Developer] Subquery 서브쿼리 본문

Oracle/Group by + Subquery

[Oracle - SQL Developer] Subquery 서브쿼리

삐옥 2021. 11. 24. 08:44

 

 

 

 

 

 

 


 

 

Query 쿼리

 

Main Query, 일반 쿼리
- 하나의 SELECT(INSERT, UPDATE, DELETE)로만 되어있는 쿼리

Sub Query, 서브 쿼리, 부속 질의

- 하나의 쿼리안에 또 다른 쿼리가 들어있는 쿼리
- 하나의 SELECT(INSERT, UPDATE, DELETE)안에 또 다른 쿼리(SELECT)가 들어있는 쿼리
- 삽입 위치 > SELECT절, FROM절, WHERE절, GROUP BY절, HAVING절, ORDER BY절 등

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
-- tblCountry. 인구수가 가장 많은 나라의 이름은?
select * from tblCountry;
 
select max(population) from tblCountry;
select * from tblCountry where population = 120660;
--select name from tblCountry where population = max(population); -- where절은 집계함수를 쓸 수 없다 = 개인에 대한 질문이므로
select name from tblCountry where population = (select max(population) from tblCountry);
 
 
 
-- tblComedian. 체중이 가장 많은 사람의 이름?
select * from tblComedian;
 
select max(weight) from tblComedian; --129
select last || first from tblComedian where weight = 129;
select last || first from tblcomedian where weight = (select max(weight) from tblComedian);
 
 
-- tblInsa. 급여가 가장 많은 직원이 소속된 부서는?
select * from tblInsa;
 
select max(basicpay) from tblInsa;
select buseo from tblInsa where basicpay = 2650000;
 
 
select buseo from tblInsa where basicpay = (select max(basicpay) from tblInsa);
 
 
-- tblInsa. 전체 평균 급여보다 더 많이 받고, 서울인 직원을 가져오시오.
select * from tblInsa
    where basicpay > (select avg(basicpay) from tblInsa) and city = '서울';
 
 
-- tblInsa. '홍길동'이 근무하는 부서의 직원을 가져오시오.
select * from tblInsa where buseo = (select buseo from tblInsa where name = '홍길동')
                            and name <> '홍길동';
cs

 

 

 

SubQuery 용도 

 

1. 조건절에 비교값으로 사용
     a. 반환값이 1행 1열 > 스칼라 쿼리 > 단일값 반환(원자값) > 상수 취급 > 비교연산자로 비교..
      b. 반환값이 N행 1열 > 열거형 비교 > in 연산자
      c. 반환값이 1행 N열 > 그룹 + 연산자
      d. 반환값이 N행 N열 > b + c 혼합


2. 컬럼리스트에서 사용
      - 반드시 결과값이 1행 1열이어야 한다.(****************) > 스칼라 쿼리
      a. 정적 쿼리 > 모든 행에 동일한 값을 적용 > 사용 빈도 적음
      b. 상관 서브 쿼리 > 서브 쿼리의 값과 바깥쪽 쿼리의 값을 서로 연결 > 사용 빈도 많음

 

3. FROM절에서 사용
      - 서브쿼리의 결과셋을 또 하나의 테이블이라고 생각하고 사용
      - 인라인 뷰(Inline View)

 

4. GROUP BY, HAVING, ORDER BY > (X)

 

1
2
3
4
-- 'Munich'에 위치한 부서에 소속된 직원들 명단을 출력하세요.
select * from employees 
    where department_id = (select department_id from departments 
        where location_id = (select location_id from locations where city = 'Munich'));
cs

 

 

 

 

 


 

 

Comments