집계함수
여러 칼럼 혹은 테이블 전체 칼럼으로부터 하나의 결과값을 반환하는 함수
count, sum
count = 총 갯수를 계산해주는 함수 (ex. 테이블의 데이터는 몇개?)
select count(*) from police_station;
*는 칼럼이름
sum = 숫자 칼럼의 합계를 계산
select sum(case_number) from crime_status where status_type="발생";
select sum(case_number) from crime_status where status_type="발생" and crime_stype like "살인";
avg, min, max
avg = 숫자 칼럼의 평균
select avg(case_number) from crime_status where crime_stype like '폭력' and status_type = '검거';
min = 숫자 칼럼 중 가장 작은값
select min(case_number) from crime_status where crime_stype like '강도' and status_type ='발생';
select min(case_number) from crime_status where police_station like '중부' and status_type like '검거';
max = 숫자 칼럼 중 가장 큰값
select max(case_number) from crime_status where crime_stype like '살인' and status_type like '검거';
group by, having
group by : 그룹화하여 데이터조회
select police_station from crime_status
-> group by police_station;
select police_station from crime_status
-> group by police_station
-> order by police_station
경찰서 별 총 발생범죄 건수
select police_station, sum(case_number) 발생건수
-> from crime_status
-> where status_type like '발생'
-> group by police_station
-> order by 발생건수 desc
-> limit 10;
경찰서 별 평균 범죄 검거 건수
select police_station, avg(case_number) 평균검거건수
-> from crime_status
-> where status_type like '검거'
-> group by police_station
-> order by 평균검거건수 desc
-> limit 10;
경찰서별 평균 범죄발생 건수, 평균 범죄검거 건수
select police_station, status_type, avg(case_number)
-> from crime_status
-> group by police_station, status_type
-> limit 10;
having : 조건에 집계함수가 포함되는 경우, where대신 having 사용
경찰서 별 발생 범죄 건수 합이 4천건 이상
select police_station, sum(case_number) count
-> from crime_status
-> where status_type like '발생'
-> group by police_station
-> having count > 4000;
경찰서 별 발생 폭력, 절도의 범죄 건수 평균이 2천보다 큰 경우
select police_station, avg(case_number)
-> from crime_status
-> where (crime_stype like '폭력' or crime_stype like '절도') and status_type like '발생'
-> group by police_station
-> having avg(case_number) >= 2000;