상세 컨텐츠

본문 제목

group by의 having 사용법

My SQL

by yjh0922 2022. 5. 17. 19:50

본문

having이란?

group by 이후의 where을 사용할수 없습니다. 
having은 간단하게 생각해서 group by한 결과에 조건을 붙이고 싶을때 사용합니다.
즉, group by한 그룹의 where를 한것과 같다고 볼 수 있습니다.

 

ex 1)

-- 각 고객별로 주문 금액 평균이 520 달러 이상인 데이터만 가져오기
select c.first_name,c.last_name,avg(o.amount) as AVG
from customers c
left join orders o 
	on c.id=o.customer_id
group by c.id having avg(o.amount) >= 520;

ex 2)

-- 각 고객별로 주문 금액 최대값이 810 달러 이상인 데이터만 가져와서 내림차순으로 정렬하기.
select max(o.amount) as max, first_name,last_name
from customers c
left join orders o 
	on c.id=o.customer_id
group by c.id having max(o.amount) >= 810
order by max desc;

관련글 더보기