[SQL] SQL 학습일지 07

이소티·2023년 7월 30일

SQL

목록 보기
7/7

SubQuery 예제




1. 셀프주유의 평균가격과 SK에너지의 가장 비싼 가격 조회


select (select avg(가격) from oil_price where 셀프 = "Y") 평균, max(가격) SK에너지
from oil_price
where 상표 = "SK에너지";





  1. 상표별로 가장 비싼 가격과 상호를 Inline View 사용하여 조회


select o.상호, o.상표, s.max_price
from oil_price o, (select 상표, max(가격) max_price from oil_price group by 상표) s
where o.상표 = s.상표 and o.가격 = s.max_price;





  1. 평균가격보다 높은 주유소 상호와 가격을 Nested SubQuery를 사용하여 조회


sselect 상호, 가격 from oil_price where 가격 > (select avg(가격) from oil_price);






  1. 위에서 조회한 주유소에서 주유한 연예인의 이름과 주유소,주유일을 Nested SubQuery 사용하여 조회


select 이름, 주유소, 주유일 from refueling
where 주유소 in (select 상호 from oil_price where 가격 > (select avg(가격) from oil_price));






5. refueling 테이블과 oil_price 테이블에서 10만원 이상 주유한 연예인 이름, 상호, 상표, 주유 금액, 가격을 Inline View 사용하여 조회


select r.이름, r.주유소, o.상표, r.금액, o.가격
from (select 이름, 주유소, 금액 from refueling where 금액 > 100000) r, oil_price o
where r.주유소 = o.상호






  1. 경찰서 별로 가장 많이 발생한 범죄 건수와 범죄 유형을 조회



select c.police_station, c.crime_stype, c.case_number from crime_status c,       
    -> (select police_station, max(case_number) count from crime_status where status_type like '발생' group by police_station) m
    -> where c.police_station = m.police_station and c.case_number = m.count;







7. 강동원과 성별, 소속사가 같은 연예인의 이름, 성별, 소속사 조회




select name, sex, agency from celeb
    -> where (sex,agency) in (select sex, agency from celeb where name = '강동원');

profile
데이터 관련 학습 일지

0개의 댓글