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;