저장을 습관화

SQL - GROUP BY, HAVING, EXISTS 본문

공부/데이터베이스

SQL - GROUP BY, HAVING, EXISTS

ctrs 2023. 12. 4. 00:29

1. GROUP BY

동일한 값을 가진 행(ex. 각 국가의 고객 수 찾기)을 요약행으로 그룹화한다.

 

count(), max(), min(), sum(), avg()와 같은 집계 함수와 함께 사용되며

결과 집합을 하나 이상의 열로 그룹화하는 경우에 자주 쓰인다.

 

예시 테이블 Customers

CustomerID CustomerName ContactName Address City PostalCode Country
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F. 5021 Mexico
3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F. 5023 Mexico
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden

 

예시 1) 각 국가의 고객 수 찾기

select count(customerid), country
from customers
group by country

/* country를 기준으로 행들을 묶었을때,
동일한 country 값을 가지는 행들을 몇개인가?
이것을 customerid를 세는 것으로 계산한다. */

이하 생략..

 

예시 2) 각 국가의 고객 수를 찾고, 고객수 기준 내림차순으로 정렬

select count(customerid), country
from customers
group by country
order by count(customerid) desc

 

이하 생략..

 

예시 테이블 Orders

OrderID CustomerID EmployeeID OrderDate ShipperID
10248 90 5 1996-07-04 3
10249 81 6 1996-07-05 1
10250 34 4 1996-07-08 2

 

예시 테이블 Shippers

ShipperID ShipperName
1 Speedy Express
2 United Package
3 Federal Shipping

 

예시 3) GROUP BY With JOIN

select shippers.shippername, count(orders.orderid) as numberoforders
from orders
left join shippers on orders.shipperid = shippers.shipperid
group by shippername

 

 

 

2. HAVING

조회 조건을 주기 위해서 사용하는 where 키워드의 단점으로 집계 함수를 사용할 수 없다는 점이 있다.

이를 보완하기 위해 having 키워드를 사용한다.

 

예시 테이블 Customers

CustomerID CustomerName ContactName Address City PostalCode Country
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F. 5021 Mexico
3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F. 5023 Mexico
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden

 

예시 1) 각 국가의 고객 수를 나열하되, 고객이 5명 이상인 국가만 포함한다.

select count(customerid), country
from customers
group by country
having count(customerid) > 5

 

 

예시 2) 각 국가의 고객 수를 나열하되, 고객이 5명 이상인 국가만 포함하고, 고객 수 기준 내림차순으로 정렬한다.

select count(customerid), country
from customers
group by country
having count(customerid) > 5
order by count(customerid) desc

 

 

 

3. EXISTS

하위 쿼리에 레코드가 있는지 테스트하는데 쓰인다.

하위 쿼리가 하나 이상의 레코드를 반환한다면 true를 반환한다.

 

예시 테이블 Products

ProductID ProductName SupplierID CategoryID Unit Price
1 Chais 1 1 10 boxes x 20 bags 18
2 Chang 1 1 24 - 12 oz bottles 19
3 Aniseed Syrup 1 2 12 - 550 ml bottles 10
4 Chef Anton's Cajun Seasoning 2 2 48 - 6 oz jars 22
5 Chef Anton's Gumbo Mix 2 2 36 boxes 21.35

 

예시 테이블 Suppliers

SupplierID SupplierName ContactName Address City PostalCode Country
1 Exotic Liquid Charlotte Cooper 49 Gilbert St. London EC1 4SD UK
2 New Orleans Cajun Delights Shelley Burke P.O. Box 78934 New Orleans 70117 USA
3 Grandma Kelly's Homestead Regina Murphy 707 Oxford Rd. Ann Arbor 48104 USA
4 Tokyo Traders Yoshi Nagase 9-8 Sekimai Musashino-shi Tokyo 100 Japan

 

예시 1) products 테이블의 supplierID와 suppliers 테이블의 supplierID가 일치하며,

proudcts 테이블 기준 가격이 20보다 작을때가 있다면 해당 produceName을 반환한다.

하위 쿼리가 종료되었을때 상위 쿼리로 반환되는 내용이 있다면 suppliers 테이블의 suppliername을 반환한다.

select suppliername
from suppliers
where exists (
	select productname
	from products
	where products.SupplierID = suppliers.supplierID
	and price < 20
)

 

이하 생략..

 

예시 2) products 테이블의 supplierID와 suppliers 테이블의 supplierID가 일치하며,

proudcts 테이블 기준 가격이 22인 데이터가 있다면 해당 produceName을 반환한다.

하위 쿼리가 종료되었을때 상위 쿼리로 반환되는 내용이 있다면 suppliers 테이블의 suppliername을 반환한다.

select suppliername
from suppliers
where exists (
	select productname
	from products
	where products.SupplierID = suppliers.supplierID
	and price = 22
)

 

 

'공부 > 데이터베이스' 카테고리의 다른 글

SQL - JOINS  (0) 2023.12.08
SQL - ANY, ALL  (0) 2023.12.07
SQL - UNION  (0) 2023.12.03
SQL - ORDER BY, IN, BETWEEN, Aliases  (0) 2023.12.03
SQL - AND, OR, NOT  (0) 2023.12.03