컬럼에서 동일한 값을 가지는 로우를 그룹화하는 키워드
GROUP BY가 쓰인 쿼리의 SELECT
절에는 GROUP BY 대상 컬럼
과 그룹 함수
만 사용 가능
-> 만약, GROUP BY 대상 컬럼이 아닌 컬럼을 SELECT 하면, 에러가 발생
가져올 데이터 그룹에 조건을 지정해주는 키워드
그룹의 값 수를 세는 함수
NULL 이 있으면 COUNT에 포함되지 않음 주의!
그룹의 합을 계산하는 함수
그룹의 평균을 계산하는 함수
그룹의 최솟값을 반환하는 함수
그룹의 최대값을 반환하는 함수
그룹별로 갯수, 평균, 최대값
DROP DATABASE IF EXISTS pokemon;
CREATE DATABASE pokemon;
USE pokemon;
CREATE TABLE mypokemon (
number int,
name varchar(20),
type varchar(10),
height float,
weight float
);
INSERT INTO mypokemon (number, name, type, height, weight)
VALUES (10, 'caterpie', 'bug', 0.3, 2.9),
(25, 'pikachu', 'electric', 0.4, 6),
(26, 'raichu', 'electric', 0.8, 30),
(125, 'electabuzz', 'electric', 1.1, 30),
(133, 'eevee', 'normal', 0.3, 6.5),
(137, 'porygon', 'normal', 0.8, 36.5),
(152, 'chikoirita', 'grass', 0.9, 6.4),
(153, 'bayleef', 'grass', 1.2, 15.8),
(172, 'pichu', 'electric', 0.3, 2),
(470, 'leafeon', 'grass', 1, 25.5);
USE pokemon;
select * from mypokemon;
select type, AVG(weight)
from mypokemon
where LENGTH(name) > 5
group by type
having AVG(weight) > 20
order by 2 desc;
select type, MIN(height), MAX(height)
from mypokemon
where number < 200
group by type
having MAX(weight) >= 10 and MIN(weight) >= 2
order by 2 desc, 3 desc;
select type, AVG(height)
from mypokemon
group by type;
select type, AVG(weight)
from mypokemon
group by type;
select type, avg(height), avg(weight)
from mypokemon
group by type;
select type
from mypokemon
group by type
having AVG(height) >= 0.5;
select type
from mypokemon
group by type
having avg(weight) > 20;
select type, sum(number)
from mypokemon
group by type;
select type, count(1)
from mypokemon
where height >= 0.5
group by type;
select type, min(height)
from mypokemon
group by type;
select type, max(weight)
from mypokemon
group by type;
select type
from mypokemon
group by type
having min(height) > 0.5 and max(weight) < 30;