๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
6๏ธโƒฃ SQL/Problem Solving

[MySQL] Programmers Lv.2 ์ „์ฒด ๋ฌธ์ œ ํ’€์ด

by seolhee2750 2022. 2. 2.
๊ณ ์–‘์ด์™€ ๊ฐœ๋Š” ๋ช‡ ๋งˆ๋ฆฌ ์žˆ์„๊นŒ
SELECT ANIMAL_TYPE, COUNT(ANIMAL_TYPE) AS "count"
FROM ANIMAL_INS
GROUP BY ANIMAL_TYPE
ORDER BY ANIMAL_TYPE

 

์ตœ์†Ÿ๊ฐ’ ๊ตฌํ•˜๊ธฐ
SELECT MIN(DATETIME) AS "์‹œ๊ฐ„"
FROM ANIMAL_INS

 

์ด๋ฆ„์— el์ด ๋“ค์–ด๊ฐ€๋Š” ๋™๋ฌผ ์ฐพ๊ธฐ
SELECT ANIMAL_ID, NAME
FROM ANIMAL_INS
WHERE NAME LIKE "%el%" AND ANIMAL_TYPE = "Dog"
ORDER BY NAME

๐Ÿ– LIKE๋Š” ๋ฌธ์ž์—ด์˜ ํŒจํ„ด์„ ๊ฒ€์ƒ‰ํ•˜๋Š” ์—ญํ• 

๐Ÿ– SQL์€ ๊ธฐ๋ณธ์ ์œผ๋กœ ๋Œ€์†Œ๋ฌธ์ž ๊ตฌ๋ถ„ํ•˜์ง€ ์•Š์Œ

 

์ž…์–‘ ์‹œ๊ฐ ๊ตฌํ•˜๊ธฐ(1)
SELECT HOUR(DATETIME) AS "HOUR", COUNT(DATETIME) AS "COUNT"
FROM ANIMAL_OUTS
WHERE HOUR(DATETIME) BETWEEN 9 AND 19
GROUP BY HOUR(DATETIME)
ORDER BY HOUR(DATETIME)

๐Ÿ– BETWEEN x AND y ๊ตฌ๋ฌธ ์‚ฌ์šฉ ๊ฐ€๋Šฅ, x๋ถ€ํ„ฐ y๊นŒ์ง€๋ฅผ ์˜๋ฏธ

 

+ ๋‹ค์‹œ ํ’€์–ด๋ณด๋‹ˆ ๋” ์ข‹์€ ํ’€์ด๊ฐ€ ์žˆ์—ˆ์Œ !

select hour(datetime) as `hour`, count(*) as `count`
from animal_outs
group by hour
having hour between 9 and 19
order by hour

 

์ค‘์„ฑํ™” ์—ฌ๋ถ€ ํŒŒ์•…ํ•˜๊ธฐ
-- CASE WHEN ์‚ฌ์šฉ
SELECT ANIMAL_ID, NAME, 
CASE
WHEN SEX_UPON_INTAKE LIKE "Intact%"
THEN "X"
ELSE "O"
END
AS "์ค‘์„ฑํ™”"
FROM ANIMAL_INS
ORDER BY ANIMAL_ID

-- IF ์‚ฌ์šฉ
SELECT ANIMAL_ID, NAME, 
IF (SEX_UPON_INTAKE LIKE "Intact%", "X", "O" ) AS "์ค‘์„ฑํ™”"
FROM ANIMAL_INS
ORDER BY ANIMAL_ID

๐Ÿ– CASE WHEN THEN ELSE END ๊ตฌ๋ฌธ, SELECT์—์„œ ์‚ฌ์šฉ ๊ฐ€๋Šฅ

๐Ÿ– IF๋Š” (์กฐ๊ฑด๋ฌธ, ๊ฒฐ๊ณผ, ์˜ˆ์™ธ ๊ฒฐ๊ณผ) ์œผ๋กœ ํ‘œํ˜„, SELECT์—์„œ ์‚ฌ์šฉ ๊ฐ€๋Šฅ

 

DATETIME์—์„œ DATE๋กœ ํ˜• ๋ณ€ํ™˜
SELECT ANIMAL_ID, NAME, DATE_FORMAT(DATETIME, '%Y-%m-%d') AS "๋‚ ์งœ"
FROM ANIMAL_INS
ORDER BY ANIMAL_ID

๐Ÿ– DATE_FORMAT(๋Œ€์ƒ, ์กฐ๊ฑด)์œผ๋กœ ํ‘œํ˜„

๐Ÿ– %Y๋Š” 4์ž๋ฆฌ ๋…„๋„(%y๋Š” 2์ž๋ฆฌ ๋…„๋„), %m์€ ์ˆซ์ž ์›”(%M์€ ์˜๋ฌธ ์›”), %d๋Š” ์ผ์ž๋ฅผ ํ‘œํ˜„, ๊ตฌ๋ถ„ ๊ธฐํ˜ธ ๋” ๋งŽ์Œ

 

๋ฃจ์‹œ์™€ ์—˜๋ผ ์ฐพ๊ธฐ
-- OR ์‚ฌ์šฉ
SELECT ANIMAL_ID, NAME, SEX_UPON_INTAKE
FROM ANIMAL_INS
WHERE NAME = 'Ella' OR NAME = 'Lucy' OR NAME = 'Pickle' OR NAME = 'Rogan' OR NAME = 'Mitty' OR NAME = 'Sabrina'
ORDER BY ANIMAL_ID

-- IN ์‚ฌ์šฉ
SELECT ANIMAL_ID, NAME, SEX_UPON_INTAKE
FROM ANIMAL_INS
WHERE NAME IN ('Ella', 'Lucy', 'Pickle', 'Rogan', 'Mitty', 'Sabrina')
ORDER BY ANIMAL_ID

๐Ÿ– IN์„ ์‚ฌ์šฉํ•˜์—ฌ ํŠน์ • ๊ฐ’์„ ๊ฐ€์ง€๋Š”์ง€ ํ™•์ธํ•  ์ˆ˜ ์žˆ์Œ

 

๋™๋ช… ๋™๋ฌผ ์ˆ˜ ์ฐพ๊ธฐ
SELECT NAME, COUNT(NAME) AS "COUNT"
FROM ANIMAL_INS
GROUP BY NAME
HAVING COUNT(NAME) >= 2
ORDER BY NAME

 

๋™๋ฌผ ์ˆ˜ ๊ตฌํ•˜๊ธฐ
SELECT COUNT(*) AS "count"
FROM ANIMAL_INS

 

NULL ์ฒ˜๋ฆฌํ•˜๊ธฐ
SELECT ANIMAL_TYPE, IF (NAME IS NULL, 'No name', NAME) AS NAME, SEX_UPON_INTAKE
FROM ANIMAL_INS
ORDER BY ANIMAL_ID

 

์ค‘๋ณต ์ œ๊ฑฐํ•˜๊ธฐ
SELECT COUNT(DISTINCT NAME) AS "count"
FROM ANIMAL_INS
WHERE NAME IS NOT NULL

 

๋Œ“๊ธ€