본문 바로가기
데이터분석/Python

[SQL] mySQL 문법 정리(2)- GROUP BY, HAVING

by 말랭쓰 2021. 2. 6.
320x100

 

 

2021/02/06 - [데이터분석/Python] - [SQL] mySQL 문법 정리(1)-생성,수정,삭제,삽입,선택

 

[SQL] mySQL 문법 정리(1)-생성,수정,삭제,삽입,선택

관계형 데이터베이스를 사용하는데 MySQL을 많이 사용합니다. SQL 문법을 정리하면서 데이터베이스를 생성하고, SQL에서 제공하는 데이터베이스와 테이블을 가지고 와서 기초를 정리해봅시다. 먼

sunwoo-725.tistory.com

 

지난 포스팅에서 CREATE, ALTER, DROP, INSERT, SELECT(allias, distinct, where, between A and B, order by, concat, like, in, limit)에 대해 다루었고, 나머지 문법과 쿼리문을 다뤄보겠습니다.

MySQL에서 제공하는 데이터베이스를 가져와서 사용하기 위해 아래의 사이트로 접속해서 'world' 데이터베이스를 다운로드해줍니다.

 

dev.mysql.com/doc/index-other.html

 

MySQL :: Other MySQL Documentation

Other MySQL Documentation This page provides additional documentation. There's even more available on these extra pages: MySQL Server Doxygen Documentation Title HTML Online MySQL Server (latest version) View Expert Guides Example Databases Additional Docu

dev.mysql.com

728x90

'world' 데이터베이스에는 'city', 'country', 'countrylanuage' 3개의 테이블이 있습니다.

 

- city

- country

- countrylanguage

 

world 데이터베이스 안에 있는 3가지의 테이블을 이용해 새로운 함수들을 사용해보며 정리해보겠습니다.


1. GROUP BY

: GROUP BY는 동일한 데이터를 가지는 Column을 합쳐줍니다.

그룹으로 묶어줄 때 그룹함수는 COUNT, MIN, MAX, SUM, AVG 가 있습니다.

 

1. COUNT

- countrylanguage 테이블에서 전체 언어가 몇개 있는지 출력

SELECT count(DISTINCT(LANGUAGE))
FROM countrylanguage

 

2. MIN

- country 테이블에서 대륙별 인구수와 GNP 최소 값을 조회하기

SELECT continent, MIN(Population) as Population, MIN(GNP) as GNP
FROM country
WHERE GNP != 0 AND Population != 0
GROUP BY continent

 

3. MAX

- 대륙별 인구수와 GNP의 최대값 출력

SELECT continent,max(population),max(GNP),
SUM(GNP)/SUM(Population)
FROM country
GROUP BY continent

 

4. SUM

- 대륙별 총 인구수와 총 GNP

SELECT continent, SUM(Population) as Population, SUM(GNP) as GNP
FROM country
WHERE GNP != 0 AND Population != 0
GROUP BY continent

 

5. AVG

- 대륙별 평균 인구수와 평균 GNP 결과를 인구수로 내림차순 정렬

SELECT continent, AVG(Population) as Population, AVG(GNP) as GNP
FROM country
WHERE GNP != 0 AND Population != 0
GROUP BY continent
ORDER BY Population DESC

2. HAVING

: HAVING은 WHERE와 비슷하게 조건문을 가지지만 GROUP BY 뒤에 사용되어 GROUP BY에서 반환된 결과에 조건을 줄 수 있습니다.

- 대륙별 전체인구를 구하고 5억 이상인 대륙만 출력

SELECT continent,sum(population)
FROM country
GROUP BY continent
HAVING SUM(population)>=500000000

 

300x250
반응형

댓글