본문 바로가기
코딩/SQL

[MySQL] Aggregate Functions(집계함수) count, sum, avg, min, max, group by, having

by 미생22 2023. 3. 5.
728x90

1. Aggregate Functions (집계함수)

- 여러 컬럼 혹은 테이블 전체 컬럼으로부터 하나의 결과값을 반환하는 함수

count : 총 갯수

sum : 합계

avg : 평균

min : 최소

max: 최대

first : 첫번째 결과값 기턴

last : 마지막 결과값 리턴

2. Count, sum, avg, min, max

select COUNT(column) from tablename where condition;
select SUM(column) from tablename where condition;
select AVG(column) from tablename where condition;
select MIN(column) from tablename where condition;
select MAX(column) from tablename where condition;

+ count(distinct column)을 쓰면 중복을 제거한 갯수를 확인할 수 있다.

3. Group by

- 그룹화하여 데이터를 조회

select column1, column2, ... from table where condition GROUP BY column1, column2, ... ORDER BY column1, column2, ...;

group by에서는 order 정렬도 같이 쓸 수 있다.

참고로 distinct와 같아 보이지만 distinct는 order by를 같이 사용할 수 없다.

특히 위의 집계함수와 많이 쓰는데

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

라는 예시를 통해 다음과 같은 결과를 얻을 수 있다.

4. Having

- 조건에 집계함수가 포함되는 경우 where 대신 having을 사용

select col1, col2, ... from table where condition
group by col1, col2, ... HAVING condition (Aggregate Functions) order by col1, col2, ...

문법보다 예제로 보는게 간편하다.

select police_station, sum(case_number) count from crime_status where status_tupe like '발생'
group by police_station HAVING count > 4000;

where count > 4000;이 아닌 having count>4000;이어야 한다.

 

 

728x90