본문 바로가기
sql

sql 쿼리 작성

by yura oh 2022. 12. 31.

SELECT

select p.ProductName,

(select *

from Categories c

where c.CategoryID = p.CategoryID)

from Products p

FROM

select c.CategoryName,

cp.avg

from ( select CategoryID,

avg(Price) as avg

from Products

group by CategoryID ) cp

inner join Categories c

on cp.CategoryID = c.CategoryID

WHERE

select *

from Products

where price > (select avg(price)

from Products)

서브쿼리의 결과가 단일행

select avg(price) from Products

서브쿼리의 결과가 다수행 (IN, ANY, ALL, EXSITS 사용)

select ProductID

from Products

where price > 90

where 컬럼1 = 10 or 컬럼1 = 20 or 컬럼1 = 30

where 컬럼1 in (10, 20, 30)

select *

from OrderDetails

where ProductID IN (select ProductID

from Products

where price > 90 )

서브쿼리의 결과가 다수컬럼(컬럼을 모두 언급하고 IN, ANY, ALL, EXSITS 사용)

select *

from Orders

where CustomerID, EmployeeID in (select CustomerID, EmployeeID

from Orders

where OrderDate < '1997-01-01');

IN, ANY, ALL, EXISTS 연산자

IN -> 특정 컬럼의 값이 나열한 값중 하나라도 일치하면 포함

-> 컬럼 IN (값1, 값2, 값3 ....) -----> 컬럼 = 값1 or 컬럼 = 값2 or 컬럼 = 값3

ANY / ALL -> 특정 컬럼의 값이 나열한 값중 조건을 만족 하면 포함(대소 비교 가능)

-> ANY : 컬럼 > ANY (값1, 값2, 값3 ...) ----> 컬럼 > 값1 or 컬럼 > 값2 or 컬럼 >값3

-> ALL : 컬럼 > ALL (값1, 값2, 값3 ...) ----> 컬럼 > 값1 and 컬럼 > 값2 and 컬럼 >값3

EX)

상품 중에서 카테고리가 2인 상품들의 가격들 중 최저 가격보다 높은 모든 상품들

select *

from Products

where Price > ANY (select Price

from Products

where CategoryID = 2)

상품 중에서 카테고리가 2인 상품들의 가격들 중 최고 가격보다 낮은 모든 상품들

select *

from Products

where Price < ANY (select Price

from Products

where CategoryID = 2)

위 쿼리가 맞는지 검산

select *

from Products

where price >= (select max(price)

from Products

where CategoryID = 2 )

EXISTS -> 서브쿼리가 참이면 메인쿼리 실행

select *

from 테이블

where exists (서브쿼리)

EX)

주문을 한번이라도 한 고객 찾기

select *

from Customers c

where

not exists (select *

from Orders o

where c.CustomerID = o.CustomerID)

'sql' 카테고리의 다른 글

sql 서브쿼리  (0) 2023.01.02
데이터분석  (0) 2022.12.27
dbms //01  (0) 2022.12.22