SQL 24, 25

이재훈·2024년 2월 10일
1

Zerobase_DA3_SQL

목록 보기
14/16

Aggregate Functions (집계함수)

Group By

그룹화화여 데이터를 조회

Select column2, column2
From table
Where condition
Group by column1, column2
order by column1, column2

경찰서별 범죄 건수 검색

select police_station, sum(case_number) 발생건수
from crime_status
where status_type LIKE "발생"
group by police_station
order by 발생건수 desc;

경찰서별 평균 검거 건수

select police_station, avg(case_number) 평균검거건수
from crime_status
where status_type LIKE '검거'
group by police_station
order by 평균검거건수 desc
LIMIT 5;

HAVING

조건에 집계함수가 포함되는 경우 WHERE 대신 HAVING사용

경찰서별로 발생한 범죄 건수의 합이 4000보다 큰경우 검색

select police_station, sum(case_number) count
-> from crime_status
-> where status_type LIKE "발생"
-> group by police_station
-> having count > 4000;

↓ 문제1) 경찰서별로 절도범죄 평균발생건수를 가장많은 건수순으로 10개 검색하세요.

select police_station, avg(case_number) 평균발생건수
from crime_status
where crime_stype LIKE "절도" AND status_type LIKE "발생"
group by police_station
order by 평균발생건수 desc LIMIT 10;

↓ 문제2) 경찰서별로 가장 많이 검거한 범죄 건수를 가장 적은 건수 순으로 5개 검색하세요.

select police_station, crime_stype, MAX(case_number) from crime_status
where status_type LIKE "검거"
group by police_station
order by max(case_number)
LIMIT 5;

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

select police_station,crime_stype, 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;

↓ 문제4 ) ‘대문’으로 끝나는 이름의 경찰서 별 범죄발생 건수의 평균이 500건 이상인 경우를 검색하세요.

select police_station, AVG(case_number) from crime_status
where status_type LIKE "발생" AND police_station LIKE("%대문")
group by police_station
having avg(case_number) >= 500 ;

profile
💻 To be a Data analyst

0개의 댓글