Post

SQL_6 (Aggregate Functions) [집계 함수]

🙅‍♂️휴대폰으로 볼 때 혹시 글자나 숫자가 화면에 다 안나오면, 휴대폰 가로로 돌리시면 됩니다

1
2
3
4
5
<목차>

1. count, sum 실습
2. avg, min, max 실습
3. group by, having 실습




1. count, sum 실습

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
cd C:\Users\withj\Documents\sql_ws
aws 로그인

use zerobase;
show tables;
select * from police_station;

# 5개만 보기
select * from crime_status limit 5;

# 데이터 갯수 --> 121
select count(*) from police_station;

# 고유값(중복x) --> 31개
select count(distinct police_station) from crime_status;

# 31개를 단어로 확인
select distinct police_station from crime_status;

# crime_status 테이블의 crime_type컬럼 unique() 확인
select distinct crime_type from crime_status;

# crime_status 테이블, case number 컬럼
# 조건--> status_type="발생" 합계 
select sum(case_number) from crime_status where status_type='발생';




2. avg, min, max 실습

2-1) 살인의 평균건수를 검색하고 확인하세요

1
2
3
4
5
6
7
# 평균 살인 발생률
select avg(case_number) from crime_status
where crime_type like '살인' and status_type like '발생';

# 눈으로 확인
select * from crime_status 
where crime_type like '살인' and status_type like '발생';

2-2) 광진경찰서에서 가장 낮은 범죄 검거 건수를 검색하고 확인하세요

1
2
select min(case_number) from crime_status
where police_station like '광진' and status_type like '검거';

2-3) 영등포경찰서의 가장 높은 범죄 발생 건수를 검색하고 확인하세요

1
2
select max(case_number) from crime_status
where police_station like '영등포' and status_type like '발생';





3. group by, having 실습

3-1) 경찰서 별로 절도 범죄 평균 발생 건수를 가장 많은 건수 순으로 10개 검색하고 확인하세요

1
2
3
4
5
6
7
8
9
10
11
12
13
# 2 확인
select * from crime_status limit 2;

#  문제
select police_station, avg(case_number) from crime_status
where status_type like '발생' and crime_type like '절도'
group by police_station
order by avg(case_number) desc
limit 10;

# 1 검산
select avg(case_number) from crime_status
where police_station like '송파' and status_type like '발생' and crime_type like '절도';

3-2) 경찰서 별로 가장 적게 검거한 건수 중 4건보다 큰 경우를 건수가 큰 순으로 정렬하여 검색하세요

1
2
3
4
5
6
7
8
9
# 컬럼들 확인
select * from crime_status limit 2;

#  문제
select police_station, min(case_number) from crime_status
where status_type like '검거'
group by police_station
having min(case_number) > 4
order by min(case_number) desc;
This post is licensed under CC BY 4.0 by the author.
3D GIF