GROUP BY
는 그룹화하여 데이터를 조회하는 함수이다.
GROUP BY 문법
SELECT column1, column2, ... FROM table WHERE condition GROUP BY column1, column2, ... ORDER BY column1, column2, ...;
Example 1: crime_status에서 경찰서 별로 그룹화하여 경찰서 이름을 조회하기
select police_station
from crime_status
group by police_station
order by police_station;
다음과 같이 DISTINCT
를 써도 위와 결과값이 같다.
DISTINCT
를 사용하여 경찰서 종류 검색
select distinct police_station
from crime_status;
하지만 DISTINCT
같은 경우 ORDER BY(정렬)
를 사용할 수 없다.
Example 2: 경찰서 별로 총 발생 범죄 건수 검색하기
select police_station, sum(case_number) 발생건수
from crime_status
where status_type like '발생'
group by police_station
order by 발생건수 desc;
Example 3: 경찰서 별로 평균 범죄 검거 건수 검색하기
select police_station, avg(case_number) 평균검거건수
from crime_status
where status_type like '검거'
group by police_station
order by 평균검거건수 desc
limit 10;
Example 4: 경찰서 별 평균 범죄 발생건수와 평균 범죄 검거 건수 검색하기
select police_station, status_type, avg(case_number)
from crime_status
group by police_station, status_type
limit 10;
조건에 집계함수가 포함되는 경우 WHERE 대신 HAVING
을 사용한다.
HAVING 문법
SELECT column1, column2, ... FROM table WHERE condition GROUP BY column1, column2, ... HAVING condition (Aggregate Functions) ORDER BY column1, column2, ...
Example 1: 경찰서 별로 발생한 범죄 건수의 합이 4000 건보다 큰 경우를 검색하기
select police_station, sum(case_number) 합
from crime_status
where status_type like '발생'
group by police_station
having 합 > 4000;
select sum(case_number)
from crime_status
where police_station like '영등포' and status_type like '발생';
Example 2: 경찰서 별로 발생한 폭력과 절도의 범죄 건수 평균이 2000 이상인 경우를 검색하기
select police_station, avg(case_number) as 평균
from crime_status
where status_type like '발생'
and (crime_type like '폭력' or crime_type like '절도')
group by police_station
having 평균 >= 2000;
select avg(case_number)
from crime_status
where police_station like '영등포' and status_type like '발생'
and (crime_type like '폭력' or crime_type like '절도');
select * from crime_status
where (crime_type like '폭력' or crime_type like '절도')
and status_type like '발생' and police_station like '영등포';