12 Fri
๋ฐ์ดํฐ ๋ถ์์ ์ํ ๊ณ ๊ธ SQL
์๋ธ์ฟผ๋ฆฌ
์ฟผ๋ฆฌ ์์ ๋ค์ด๊ฐ๋ ์ฟผ๋ฆฌ
SELECT, FROM, WHERE์ ์ ๋ค ์ฌ์ฉ ๊ฐ๋ฅ
SELECT๋ ๋์ ํฉ์ ๊ตฌํ ๋ ๋ง์ด ์ฌ์ฉ
FROM์ ์๋ธ์ฟผ๋ฆฌ
SELECT daily_stats.week, AVG(daily_stats.incidents_daily)
FROM (
SELECT week, date, COUNT(incident_id) AS Incidents_daily
FROM crimes
GROUP BY week, data
) daily_stats
GROUP BY daily_stats.week
๊ฐ ์ฃผ์ ๋ ์ง ๋ณ๋ก ๋ฒ์ฃ ๋ฐ์์ ์ ๋ฆฌํ ํ ์ด๋ธ์ด ์กด์ฌํ๋ค.
์ฃผ์ ๋ ์ง๋ก ์ ๋ฆฌํ ํ ์ด๋ธ์์ ๋ค์ ๋ ์ง ๋ณ๋ก ๋ฒ์ฃ ๋ฐ์ ๊ฑด์๋ฅผ ๋ณด๋ ์ฟผ๋ฆฌ์ด๋ค.
์ด ๋ ํ๋ฃจ ํ๊ท ๋ฒ์ฃ ๋ฐ์ ๊ฑด์๋ฅผ ์๊ธฐ ์ํด AVG๋ฅผ ์ป์ง๋ง, ํน์ ๋ ์ง์ ๋ํ ๋ฒ์ฃ ๋ฐ์์ด ์์ ๊ฒฝ์ฐ ์ด๋ฅผ 0์ผ๋ก ๊ฐ์ฃผํ๋ ๊ฒ์ด ์๋๋ผ NULL ๋ฐ์ดํฐ๋ก ์ธ์ํ๊ธฐ ๋๋ฌธ์ ํ๊ท ์ ๊ตฌํ ๋ ์ด๋ฅผ ์ ์ํด์ผ ํ๋ค.
EX) 1+ 2+ 3+0/4 ์ด ์๋ 1+2+3/3 ์ผ๋ก ๊ณ์ฐํ๊ธฐ ๋๋ฌธ์ ์ ์
WHERE์ ์๋ธ์ฟผ๋ฆฌ
SELECT *
FROM Crimes
WHERE date = (SELECT MIN(date) FROM Crimes)
SELECT *
FROM Crimes
WHERE date IN (SELECT date FROM Crimes
ORDER BY date DESC LIMIT 5)
1~3 : date๊ฐ
=
๋ก ๋น๊ต๋๊ณ ์์ผ๋ฏ๋ก ์๋ธ ์ฟผ๋ฆฌ๋ฌธ์ ๊ฒฐ๊ณผ๊ฐ ํ๋์ฌ์ผ ํ๋ค.5~8 : 5๊ฐ์ ๊ฒฐ๊ณผ๋ฌผ์ด ๋์ค๋ฏ๋ก
IN
์ ์ฌ์ฉํ๋ ๋ชจ์ตMIN(date)
: ๊ฐ์ฅ ์ค๋๋ ๋ ์ง,MAX(date)
: ๊ฐ์ฅ ์ต์ ๋ ์ง
HackerRank TopEarners
select salary * months, count(*)
from employee
where salary * months =
(select max(salary * months) from employee )
group by salary * months
๋๋ having ์ ์ ์ด์ฉํด์
select salary * months as earnings, count(*)
from employee
group by earnings
having earnings =
(select max(salary * months) from employee)
HackerRank Challenges
select h.hacker_id, h.name, count(*) cnt
from hackers as h
inner join challenges as c on h.hacker_id = c.hacker_id
group by h.hacker_id, h.name
having cnt = (select max(cnt)
from (
select hacker_id, count(*) cnt
from challenges
group by hacker_id ) sub)
or cnt in (select cnt
from (
select hacker_id, count(*) cnt
from challenges
group by hacker_id ) sub
group by cnt
having count(*) = 1)
order by cnt desc, h.hacker_id
With
์ ์ฝ๋๋ฅผ ๋ณด๋ฉด ๋ฐ๋ณต๋๋ ์ฝ๋๊ฐ ๋ฐ๋ณต๋๋ค. ์ฌ์ฌ์ฉ ํ๊ธฐ ์ํ ๋ฌธ๋ฒ์ผ๋ก
With
๋ฅผ ์ ๊ณตํ๋ค.
WITH Counter AS(
SELECT h.hacker_id, h.name, count(*) cnt
FROM hackers AS h
INNER JOIN challenges AS c ON h.hacker_id = c.hacker_id
GROUP BY h.hacker_id, h.name
)
SELECT Counter.hacker_id, Counter.name, Counter.cnt
FROM Counter
WHERE cnt = (SELECT MAX(cnt) From Counter)
OR cnt IN (SELECT cnt
FROM Counter
GROUP BY cnt
HAVING COUNT(*) = 1)
ORDER BY Counter.cnt DESC, Counter.hacker_id
BETWEEN์ ์กฐ์ธ์กฐ๊ฑด์ผ๋ก ์ฐ๊ธฐ
HackerRank The Report
select
case when g.grade < 8 then null
else s.name end as name,
g.grade, s.marks
from students as s
inner join grades as g on s.marks between g.min_mark and g.max_mark
order by g.grade desc, name, s.marks
2๊ฐ ์ด์ ์ ํ์กฐ์ธํ๊ธฐ
LeetCode 180
# Write your MySQL query statement below
select distinct l.num as ConsecutiveNums
from logs as l
inner join logs as l_next on l.id + 1 = l_next.id
inner join logs as l_nnext on l.id + 2 = l_nnext.id
where l.num = l_next.num and l.num = l_nnext.num
Last updated
Was this helpful?