[SQL] 데이터 그룹화 하기(GROUP BY, HAVING, 그룹화 관련 함수)

WOOK JONG KIM·2022년 12월 14일
0

mysql기초

목록 보기
5/13
post-thumbnail

GROUP BY

컬럼에서 동일한 값을 가지는 로우를 그룹화하는 키워드

GROUP BY가 쓰인 쿼리의 SELECT 절에는 GROUP BY 대상 컬럼그룹 함수만 사용 가능
-> 만약, GROUP BY 대상 컬럼이 아닌 컬럼을 SELECT 하면, 에러가 발생

HAVING

가져올 데이터 그룹에 조건을 지정해주는 키워드

그룹화에 사용되는 함수들

COUNT

그룹의 값 수를 세는 함수

  • COUNT([컬럼 이름]) 형식으로 SELECT, HAVING 절에서 사용
  • COUNT(1)은 하나의 값을 1로 세어주는 표현으로 COUNT 함수에 자주 사용
  • GROUP BY가 없는 쿼리에서도 사용 가능하며, 이때는 전체 로우에 함수가 적용

NULL 이 있으면 COUNT에 포함되지 않음 주의!

SUM

그룹의 합을 계산하는 함수

AVG

그룹의 평균을 계산하는 함수

MIN

그룹의 최솟값을 반환하는 함수

MAX

그룹의 최대값을 반환하는 함수

그룹별로 갯수, 평균, 최대값


6가지 쿼리 핵심 키워드


코드 예시

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;
profile
Journey for Backend Developer

0개의 댓글