๊ด€๋ฆฌ ๋ฉ”๋‰ด

ruriruriya

[DB] ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค MySQL - COUNT(), SUM(), AVG(), MAX(), MIN() ํ•จ์ˆ˜ ์‚ฌ์šฉ๋ฒ• ๋ณธ๋ฌธ

๐Ÿ›ข๏ธDB/MySQL

[DB] ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค MySQL - COUNT(), SUM(), AVG(), MAX(), MIN() ํ•จ์ˆ˜ ์‚ฌ์šฉ๋ฒ•

๋ฃจ๋ฆฌ์•ผใ…‘ 2023. 11. 30. 11:27
๋ฐ˜์‘ํ˜•

MySQL์—์„œ ์ œ๊ณตํ•˜๋Š” ์ง‘๊ณ„ ํ•จ์ˆ˜๋“ค์ธ COUNT(), SUM(), AVG(), MAX(), MIN()์€ ๋ฐ์ดํ„ฐ์˜ ์ง‘ํ•ฉ์„ ๋ถ„์„ํ•˜๊ฑฐ๋‚˜ ์š”์•ฝํ•˜๋Š” ๋ฐ์— ์‚ฌ์šฉ๋œ๋‹ค.

 

์‚ฌ์šฉํ•  ํ…Œ์ด๋ธ”(books)

 

COUNT()

๋ฐ์ดํ„ฐ์˜ ๊ฐฏ์ˆ˜๋ฅผ ์„ธ๋Š” ํ•จ์ˆ˜

books ํ…Œ์ด๋ธ”์˜ ์ „์ฒด ๋ฐ์ดํ„ฐ๋Š” ๋ช‡๊ฐœ?

select count(*)
from books;

author_lname ์€ ์ค‘๋ณต๋ฐ์ดํ„ฐ๊ฐ€ ์žˆ๋‹ค.
๋”ฐ๋ผ์„œ, ์ค‘๋ณต๋ฐ์ดํ„ฐ ์ œ๊ฑฐํ•œ ์œ ๋‹ˆํฌํ•œ ๋ฐ์ดํ„ฐ์˜ ๊ฐฏ์ˆ˜๋Š” ๋ช‡๊ฐœ?

select count(distinct author_lname)
from books;

์ฑ… ์ œ๋ชฉ์— the ๊ฐ€ ๋“ค์–ด์žˆ๋Š” ์ฑ…์€, ๋ช‡ ๊ถŒ์ž…๋‹ˆ๊นŒ?

select count(*)
from books
where title like '%the%';

 

SUM()

๊ฐ’์„ ๋”ํ•ด์ฃผ๋Š” ํ•จ์ˆ˜

books ํ…Œ์ด๋ธ”์˜ ๋ชจ๋“  ์ฑ…์˜ ํŽ˜์ด์ง€์ˆ˜๋ฅผ ๋‹ค ๋” ํ•˜๋ฉด?

select sum(pages)
from books;

AVG()

ํ‰๊ท  ๊ตฌํ•˜๋Š” ํ•จ์ˆ˜ 

books ํ…Œ์ด๋ธ”์˜ ํŽ˜์ด์ง€ ์ˆ˜ ํ‰๊ท ?

select avg(pages)
from books;

MAX()

์ตœ๋Œ€๊ฐ’ ๊ตฌํ•˜๋Š” ํ•จ์ˆ˜.

ํŽ˜์ด์ง€์ˆ˜๊ฐ€ ๊ฐ€์žฅ ๋งŽ์€ ์ฑ…์€, ๋ช‡ ํŽ˜์ด์ง€๊ฐ€ ์ž…๋‹ˆ๊นŒ?

select *
from books
order by pages desc
limit 0, 1; 
-- ์ •๋ ฌํ•ด์„œ ์œ„์— ๋ฐ์ดํ„ฐ๋งŒ ๊ฐ€์ ธ์˜ค๋Š” ๋ฐฉ๋ฒ•(limit ํ‚ค์›Œ๋“œ ํ•จ๊ป˜ ์‚ฌ์šฉ)

ํ•จ์ˆ˜ ์จ์„œ ๋ฐ์ดํ„ฐ ๊ฐ€์ ธ์˜ค๋Š” ๋ฐฉ๋ฒ•

select max(pages)
from books;

 

MIN()

์ตœ์†Œ๊ฐ’ ๊ตฌํ•˜๋Š” ํ•จ์ˆ˜.

์ถœํŒ๋…„๋„๊ฐ€ ๊ฐ€์žฅ ๋น ๋ฅธ ์ฑ…์€ ๋ช‡๋…„๋„ ์ธ๊ฐ€?

select min(released_year)
from books;

ํŽ˜์ด์ง€์˜ ์ตœ์†Œ๊ฐ’๊ณผ ์ตœ๋Œ€๊ฐ’์„ ํ•จ๊ป˜ ๋ณด์—ฌ์ฃผ์‹œ์˜ค.

select min(pages) as pages_min,max(pages) as pages_max
from books;

์ด ํ•จ์ˆ˜๋“ค์„ ์‚ฌ์šฉํ•˜์—ฌ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์˜ ์š”์•ฝ ์ •๋ณด๋ฅผ ๋น ๋ฅด๊ฒŒ ์–ป์„ ์ˆ˜ ์žˆ์œผ๋ฉฐ, ๋ฐ์ดํ„ฐ์˜ ํŠน์ง•์„ ํŒŒ์•…ํ•˜๊ฑฐ๋‚˜ ์š”์•ฝ๋œ ์ •๋ณด๋ฅผ ์ œ๊ณตํ•˜๋Š” ๋ฐ ์œ ์šฉํ•˜๊ฒŒ ํ™œ์šฉ๋œ๋‹ค.

๋ฐ˜์‘ํ˜•