[MySQL] 2. SQL - SUM,MAX,MIN

sorzzzzyยท2021๋…„ 8์›” 13์ผ
0

MySQL

๋ชฉ๋ก ๋ณด๊ธฐ
2/8
post-thumbnail
post-custom-banner

๐Ÿท SUM

โœ”๏ธ SUM ํ‚ค์›Œ๋“œ๋Š” ํ•œ ์†์„ฑ์— ํ•ด๋‹นํ•˜๋Š” ๊ฐ’๋“ค์˜ ํ•ฉ์„ ๊ณ„์‚ฐํ•  ๋•Œ ์‚ฌ์šฉํ•œ๋‹ค!

SELECT SUM(์นผ๋Ÿผ๋ช…) FROM ํ…Œ์ด๋ธ”๋ช… WHERE ์กฐ๊ฑด



๐Ÿท MIN

โœ”๏ธ MIN ํ‚ค์›Œ๋“œ๋Š” ํ•œ ์†์„ฑ์— ํ•ด๋‹นํ•˜๋Š” ๊ฐ’๋“ค์˜ ์ตœ์†Œ๊ฐ’์„ ๊ตฌํ•  ๋•Œ ์‚ฌ์šฉํ•œ๋‹ค.

SELECT MIN(์นผ๋Ÿผ๋ช…) FROM ํ…Œ์ด๋ธ”๋ช… WHERE ์กฐ๊ฑด'



๐Ÿท MAX

โœ”๏ธ MAX ํ‚ค์›Œ๋“œ๋Š” ํ•œ ์†์„ฑ์— ํ•ด๋‹นํ•˜๋Š” ๊ฐ’๋“ค์˜ ์ตœ๋Œ€๊ฐ’์„ ๊ตฌํ•  ๋•Œ ์‚ฌ์šฉํ•œ๋‹ค.

SELECT MAX(์นผ๋Ÿผ๋ช…) FROM ํ…Œ์ด๋ธ”๋ช… WHERE ์กฐ๊ฑด'


๐Ÿ’ก AVG COUNT ๊นŒ์ง€ ํฌํ•จํ•ด์„œ 5๊ฐœ๋ฅผ ์ง‘๊ณ„ํ•จ์ˆ˜ ๋ผ๊ณ  ๋ถ€๋ฅธ๋‹ค!
๊ทธ๋ฆฌ๊ณ  ๊ทธ๋ฃน์œผ๋กœ ๋‚˜๋ˆ„์–ด ์ง‘๊ณ„ํ•˜๋Š” GROUP BY ํ‚ค์›Œ๋“œ์™€,
์ง‘๊ณ„ํ•จ์ˆ˜์˜ ๊ฒฐ๊ณผ๋ฅผ ํ†ตํ•ด ์กฐ๊ฑด์„ ์„ค์ •ํ•  ๋•Œ ์‚ฌ์šฉํ•˜๋Š” HAVING ํ‚ค์›Œ๋“œ๋„ ์žˆ๋‹ค.


์ฐธ๊ณ  ์ž๋ฃŒ 1



๐Ÿท ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค(SQL-Kit SUM,MIN,MAX)๋ฌธ์ œ ํ’€์ด


1. ์ตœ๋Œ“๊ฐ’ ๊ตฌํ•˜๊ธฐ

SELECT MAX(DATETIME) FROM ANIMAL_INS;

๐Ÿคš๐Ÿป ํ—ท๊ฐˆ๋ฆฌ์ง€ ๋ง๊ธฐ
์—ด ์ „์ฒด๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฒƒ์ด ์•„๋‹Œ ๊ฐ’ ํ•˜๋‚˜๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋ฉด ๋˜๊ธฐ ๋•Œ๋ฌธ์— MAX๋ฅผ ์“ฐ๋ฉด ๋œ๋‹ค!

2. ์ตœ์†Ÿ๊ฐ’ ๊ตฌํ•˜๊ธฐ

SELECT MIN(DATETIME) FROM ANIMAL_INS;

3. ๋™๋ฌผ ์ˆ˜ ๊ตฌํ•˜๊ธฐ

SELECT COUNT(*) FROM ANIMAL_INS;

COUNT ํ‚ค์›Œ๋“œ๋Š” ํ•ด๋‹น ์†์„ฑ์— ํ•ด๋‹นํ•˜๋Š” ๊ฐ’๋“ค์˜ ๊ฐœ์ˆ˜๋ฅผ ๊ตฌํ•  ๋•Œ ์‚ฌ์šฉํ•œ๋‹ค.
COUNT๋Š” NULL ๊ฐ’์€ ์ œ์™ธํ•˜๊ณ  COUNTํ•œ๋‹ค.
๐Ÿ’ก COUNT(*)๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด NULL๋„ ํฌํ•จํ•˜์—ฌ ์ „๋ถ€ COUNT !!
But, ๋นˆ ๋ฌธ์ž์—ด์€ COUNT() ๊ฒฐ๊ณผ์— ํฌํ•จ๋œ๋‹ค.
๋งŒ์•ฝ, ๋นˆ ๋ฌธ์ž์—ด์„ COUNT() ๊ฒฐ๊ณผ์—์„œ ๋นผ๊ณ ์‹ถ๋‹ค๋ฉด, ๋นˆ ๋ฌธ์ž์—ด์„ NULL๋กœ ๋ฐ”๊พธ๊ณ  COUNT ํ•ด์•ผ ํ•จ
์ฐธ๊ณ  ์ž๋ฃŒ 2


4. ์ค‘๋ณต ์ œ๊ฑฐํ•˜๊ธฐ

SELECT COUNT(DISTINCT(NAME)) FROM ANIMAL_INS;

์ค‘๋ณต์„ ์ œ๊ฑฐํ•˜๊ณ  ์นด์šดํŠธ ํ•˜๋ ค๋ฉด DISTINCT ํ‚ค์›Œ๋“œ๋ฅผ ์‚ฌ์šฉ


profile
Backend Developer
post-custom-banner

0๊ฐœ์˜ ๋Œ“๊ธ€