๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค/์•Œ๊ณ ๋ฆฌ์ฆ˜ ํ’€์ด(SQL)

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค_๊ณ ์–‘์ด์™€ ๊ฐœ๋Š” ๋ช‡ ๋งˆ๋ฆฌ ์žˆ์„๊นŒ

by carrot0911 2024. 11. 11.

๋ฌธ์ œ ์„ค๋ช…

https://school.programmers.co.kr/learn/courses/30/lessons/59040

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

SW๊ฐœ๋ฐœ์ž๋ฅผ ์œ„ํ•œ ํ‰๊ฐ€, ๊ต์œก, ์ฑ„์šฉ๊นŒ์ง€ Total Solution์„ ์ œ๊ณตํ•˜๋Š” ๊ฐœ๋ฐœ์ž ์„ฑ์žฅ์„ ์œ„ํ•œ ๋ฒ ์ด์Šค์บ ํ”„

programmers.co.kr

ANIMAL_INS ํ…Œ์ด๋ธ”์€ ๋™๋ฌผ ๋ณดํ˜ธ์†Œ์— ๋“ค์–ด์˜จ ๋™๋ฌผ์˜ ์ •๋ณด๋ฅผ ๋‹ด์€ ํ…Œ์ด๋ธ”์ž…๋‹ˆ๋‹ค. ANIMAL_INS ํ…Œ์ด๋ธ” ๊ตฌ์กฐ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์œผ๋ฉฐ, ANIMAL_ID, ANIMAL_TYPE, DATETIME, INTAKE_CONDITION, NAME, SEX_UPON_INTAKE๋Š” ๊ฐ๊ฐ ๋™๋ฌผ์˜ ์•„์ด๋””, ์ƒ๋ฌผ ์ข…, ๋ณดํ˜ธ ์‹œ์ž‘์ผ, ๋ณดํ˜ธ ์‹œ์ž‘ ์‹œ ์ƒํƒœ, ์ด๋ฆ„, ์„ฑ๋ณ„ ๋ฐ ์ค‘์„ฑํ™” ์—ฌ๋ถ€๋ฅผ ๋‚˜ํƒ€๋ƒ…๋‹ˆ๋‹ค.

NAME TYPE NULLABLE
ANIMAL_ID VARCHAR(N) FALSE
ANIMAL_TYPE VARCHAR(N) FALSE
DATETIME DATETIME FALSE
INTAKE_CONDITION VARCHAR(N) FALSE
NAME VARCHAR(N) TRUE
SEX_UPON_INTAKE VARCHAR(N) FALSE

๋ฌธ์ œ

๋™๋ฌผ ๋ณดํ˜ธ์†Œ์— ๋“ค์–ด์˜จ ๋™๋ฌผ ์ค‘ ๊ณ ์–‘์ด์™€ ๊ฐœ๊ฐ€ ๊ฐ๊ฐ ๋ช‡ ๋งˆ๋ฆฌ์ธ์ง€ ์กฐํšŒํ•˜๋Š” SQL๋ฌธ์„ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”. ์ด๋•Œ ๊ณ ์–‘์ด๋ฅผ ๊ฐœ๋ณด๋‹ค ๋จผ์ € ์กฐํšŒํ•ด์ฃผ์„ธ์š”.

์˜ˆ์‹œ

์˜ˆ๋ฅผ ๋“ค์–ด ANIMAL_INS ํ…Œ์ด๋ธ”์ด ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค๋ฉด

ANIMAL
_ID
ANIMAL
_TYPE
DATETIME INTAKE
_CONDITION
NAME SEX_UPON
_INTAKE
A373219 Cat  2014-07-29
11:43:00
Normal Ella Spayed Female
A377750 Dog 2017-10-25
17:17:00
Normal Lucy Spayed Female
A354540 Cat 2014-12-11
11:48:00
Normal Tux Neutered Male

๊ณ ์–‘์ด๋Š” 2๋งˆ๋ฆฌ, ๊ฐœ๋Š” 1๋งˆ๋ฆฌ ๋“ค์–ด์™”์Šต๋‹ˆ๋‹ค. ๋”ฐ๋ผ์„œ SQL๋ฌธ์„ ์‹คํ–‰ํ•˜๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์ด ๋‚˜์™€์•ผ ํ•ฉ๋‹ˆ๋‹ค.

ANIMAL_TYPE count
Cat 2
Dog 1

 

๋‚ด๊ฐ€ ์ž‘์„ฑํ•œ ์ฝ”๋“œ

SELECT ANIMAL_TYPE, count(*) AS 'count'
FROM ANIMAL_INS
GROUP BY ANIMAL_TYPE
ORDER BY ANIMAL_TYPE;

์ฝ”๋“œ ์„ค๋ช…

  • SELECT ANIMAL_TYPE, count(*) AS 'count' : ANIMAL_TYPE ์ปฌ๋Ÿผ๊ณผ ํ•จ๊ป˜ ๊ฐœ์ˆ˜๋ฅผ ๊ตฌํ•˜๊ณ  count ์ปฌ๋Ÿผ์œผ๋กœ ๋‚˜ํƒ€๋‚ธ๋‹ค.
  • FROM ANIMAL_INS : ANIMAL_INS ํ…Œ์ด๋ธ”์—์„œ ๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ€์ ธ์˜จ๋‹ค.
  • GROUP BY ANIMAL_TYPE : ANIMAL_TYPE ์ปฌ๋Ÿผ ๋ณ„๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ๊ทธ๋ฃนํ™”ํ•œ๋‹ค.
  • ORDER BY ANIMAL_TYPE : ANIMAL_TYPE ์ปฌ๋Ÿผ์„ ๊ธฐ์ค€์œผ๋กœ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌํ•œ๋‹ค.