SUBQUERY(서브쿼리)는 하나의 SQL문 안에 또 다른 SQL문으로, 주로 외부 쿼리의 데이터 필터링, 검색, 비교 연산 등을 수행한다.
데이터 테이블인 police_station(경찰 데이터 테이블)과 crime_status(범죄 데이터 테이블)를 사용하여 원하는 데이터를 추출
문제: 서울은평경찰서의 강도 검거 건수와 서울시 경찰서 전체의 평균 강도 검거 건수를 조회
select case_number
from crime_status
where police_station = '은평' and crime_typr = '강도' and status_type = '검거';
select avg(case_number)
from crime_status
where crime_typr = '강도' and status_type = '검거';
3. 서울은평경찰서의 강도 검거 건수와 서울시 경찰서 전체의 평균 강도 검거 건수를 조회
select case_number as 은평건수,
(select avg(case_number)
from crime_status
where crime_typr = '강도' and status_type = '검거') as 평균건수
from crime_status
where police_station = '은평' and crime_typr = '강도' and status_type = '검거';
문제: 경찰서 별로 가장 많이 발생한 범죄 건수와 범죄 유형을 조회
select police_station, crime_type, case_number
from crime_status
where status_type = '발생'
group by police_station;
2. 경찰서 별로 가장 많이 발생한 범죄 건수와 범죄 유형을 조회
select A.police_station, A.crime_type, A.case_number as all_count
from crime_status as A,
(select police_statios, max(case_number) as max_count
from crime_status
where status_type = '발생'
group by police_station) as B
where A.police_station = B.police_station and all_count = max_count;
중첩 서브쿼리는 3가지 종류가 있다.
1. Single Row: 하나의 행 데이터를 검색하는 서브쿼리
2. Multiple Row: 하나 이상의 행 데이터를 검색하는 서브쿼리
3. Multiple Column: 하나 이상의 열 데이터를 검색하는 서브쿼리
select *
from crime_status
where reference = (select name from police_station where name = '서울노원경찰서');
select *
from crime_status
where reference in (select name from police_station where length(name) = 24);
//경찰서 지역"노원"과 같은 범죄 타입, 현황 타입을 조회
select crime_type, status_type
from crime_status
where (crime_type, status_type, reference) in
(select crime_type, status_type, reference from crime_status where police_station = '노원');