Study_note(zb_data)/SQL
์คํฐ๋ ๋ ธํธ (SQL ์ง๊ณํจ์, group by, having)
KloudHyun
2023. 8. 30. 20:14
๐ Aggregate Functions (์ง๊ณํจ์)
- ์ฌ๋ฌ ์นผ๋ผ ํน์ ๋ฐ์ด๋ธ ์ ์ฒด ์นผ๋ผ์ผ๋ก๋ถํฐ ํ๋์ ๊ฒฐ๊ณผ ๊ฐ์ ๋ฐํํ๋ ํจ์
๐ GROUP BY
- ๊ทธ๋ฃนํํ์ฌ ๋ฐ์ดํฐ ์กฐํ
- ์ค๋ณต ์ ๊ฑฐ๋ฅผ ๋๊ณ ๋ดค์ ๋, distinct์ ์ ์ฌํ ๊ธฐ๋ฅ (but distinct๋ order by๋ฅผ ์ฌ์ฉํ ์ ์๋ค)
๐งท ์์
select police_station, sum(case_number) from crime_status
where status_type = '๋ฐ์'
group by police_station
order by sum(case_number) desc;
select police_station, status_type, avg(case_number)
from crime_status
group by police_station, status_type;
๐ HAVING
- ์กฐ๊ฑด์ ์ง๊ณ ํจ์๊ฐ ํฌํจ๋๋ ๊ฒฝ์ฐ, where ๋์ having ์ฌ์ฉ ๊ฐ๋ฅ
select column1, column2, ... from table
where condition
group by column1, column2, ...
having condition (aggregate functions)
order by column1, column2, ...
๐งท ์์
select police_station, sum(case_number) count from crime_status
where status_type = '๋ฐ์'
group by police_station
having count > 4000;
select police_station, avg(case_number) count from crime_status
where (crime_type = 'ํญ๋ ฅ' or crime_type = '์ ๋') and status_type = '๋ฐ์'
group by police_station
having count >= 2000;