๊ณ ์์ด์ ๊ฐ๋ ๋ช ๋ง๋ฆฌ ์์๊น
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
'6๏ธโฃ SQL > Problem Solving' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[MySQL] Programmers Lv.2 ์ ์ฒด ๋ฌธ์ ํ์ด (2023 ์ ๋ฐ์ดํธ!) (1) | 2023.06.27 |
---|---|
[MySQL] Programmers Lv.1 ์ ์ฒด ๋ฌธ์ ํ์ด (2023 ์ ๋ฐ์ดํธ!) (2) | 2023.04.26 |
[MySQL] Programmers Lv.4 ์ ์ฒด ๋ฌธ์ ํ์ด (0) | 2022.02.02 |
[MySQL] Programmers Lv.3 ์ ์ฒด ๋ฌธ์ ํ์ด (0) | 2022.02.02 |
[MySQL] Programmers Lv.1 ์ ์ฒด ๋ฌธ์ ํ์ด (0) | 2022.02.02 |
๋๊ธ