MYSQL

그룹화하기 (GROUP BY, COUNT(*))

soo15 2023. 5. 19. 18:23

 

Products Table

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
6 Grandma's Boysenberry Spread 3 2 12 - 8 oz jars 25
7 Uncle Bob's Organic Dried Pears 3 7 12 - 1 lb pkgs. 30
8 Northwoods Cranberry Sauce 3 2 12 - 12 oz jars 40
:
:
:
:
:
:
:
:
:
:
:
:

 

 

1. SupplierID로 그룹화

GRUOP별로 출력된다.
GRUOP BY절에 쓴 값은 반드시 SELECT절에도 작성해야 한다.
SELECT *, COUNT(*)
	FROM Products
    	GROUP BY SupplierID

 

 

출력결과

ProductID ProductName SupplierID CategoryID Unit Price COUNT(*)
1 Chais 1 1 10 boxes x 20 bags 18 3
4 Chef Anton's Cajun Seasoning 2 2 48 - 6 oz jars 22 4
6 Grandma's Boysenberry Spread 3 2 12 - 8 oz jars 25 3
:
:
:
:
:
:
:
:
:
:
:
:
:
:

> SupplierID로 그룹화하면 SupplierID별COUNT된다.

> 모든 컬럼에는 SupplierID별로 나누었을 때 가장 위에 있는 값이 출력된다.

 

 

 

 

 

2. CategoryID로 그룹화

어떤 컬럼을 그룹화를 했느냐에 따라 값이 다르다.
SELECT *, COUNT(*)
	FROM Products
    	GROUP BY CategoryID

 

출력결과

 

ProductID ProductName SupplierID CategoryID Unit Price COUNT(*)
1 Chais 1 1 10 boxes x 20 bags 18 12
3 Aniseed Syrup 1 2 12 - 550 ml bottles 10 12
16 Pavlova 7 3 32 - 500 g boxes 17.45 13
:
:
:
:
:
:
:
:
:
:
:
:
:
:

> CategoryID로 그룹화하면 CategoryID별COUNT된다.

> 위의 '1. SupplierID로 그룹화' 할 때랑 COUNT의 값이 다르다.

> 모든 컬럼에는 CategoryID별로 나누었을 때 가장 위에 있는 값이 출력된다.

 

 

 

 

 

3. SupplierID, CategoryID로 그룹화

두 개의 값이 그룹화된다.
예) (SupplierID, CategoryID) > (1, 1), (1, 2), (2, 2), ...
SELECT *, COUNT(*)
	FROM Products
    	GROUP BY SupplierID, CategoryID

 

출력결과

ProductID ProductName SupplierID CategoryID Unit Price COUNT(*)
1 Chais 1 1 10 boxes x 20 bags 18 2
3 Aniseed Syrup 1 2 12 - 550 ml bottles 10 1
4 Chef Anton's Cajun Seasoning 2 2 48 - 6 oz jars 22 4
6 Grandma's Boysenberry Spread 3 2 12 - 8 oz jars 25 2
7 Uncle Bob's Organic Dried Pears 3 7 12 - 1 lb pkgs. 30 1
:
:
:
:
:
:
:
:
:
:
:
:
:
:

> SupplierID, CategoryID로 그룹화하면 (SupplierID, CategoryID)별COUNT된다.

> 모든 컬럼에는 (SupplierID, CategoryID)별로 나누었을 때 가장 위에 있는 값이 출력된다.

 

 

 

 

참고)

2023.05.19 - [SQL/초급] - MAX, MIN, SUM, AVG, COUNT 사용하기 (GROUP BY, HAVING)