Subquery
๐ ์ฟผ๋ฆฌ๋ฌธ ์์ ๋๋ค๋ฅธ ์ฟผ๋ฆฌ๋ฌธ์ ์์ฑํ๋ ๊ฒ.
๐ where์ , from ์ , select ์ ์์ ์ด์ฉ.
where ์ ์์ ์ฌ์ฉํ Subquery in
๐ Subquery์ ๊ฒฐ๊ณผ๋ฅผ ์กฐ๊ฑด์ ํ์ฉ
๐ where ํ๋๋ช in (subquery)
๐ where ํ๋๋ช ์ด (์๋ธ์ฟผ๋ฆฌ) ์ ํด๋นํ ๋~~ ์ด๋ฐ๋ง. = ๊ธฐํธ ์๋๊ณ in ์จ์ผํจ!
select user_id, name, email from users
where user_id in (
select user_id from orders
where payment_method = 'kakaopay'
)
โ๏ธ Query ๐ users ํ ์ด๋ธ ์์, user_id์, name์ ๊ฐ์ง๊ณ ์ค๋๋ฐ,
โ๏ธ Subquery ๐ orders ํ ์ด๋ธ์์ payment_method๊ฐ kakaopay์ธ user_id
โ๏ธ where์ ๐ ์ ํด๋นํ๋ user_id๋ฅผ ๊ฐ์ง๊ณ ์๋ ์ ๋ค๋ง ๊ฐ์ ธ์์ค.
select ๋ฌธ ์์ ์ฌ์ฉํ Subquery
๐ ๊ธฐ์กด ํ ์ด๋ธ์ ์ถ๊ฐ ํ๊ณ ์ถ์ ํต๊ณ ๋ฐ์ดํฐ๋ฅผ ์ฝ๊ฒ ๋ถ์ผ ์ ์์.
๐ select ํ๋๋ช , ํ๋๋ช , (subquery) as ๋ณ์นญ
select c.checkin_id,
c.user_id,
c.likes,
(
select avg(likes) from checkins c2
where c2.user_id = c.user_id
) as avg_like_user
from checkins c;
โ๏ธ Query ๐ checkins c ํ ์ด๋ธ ์์, c.checkin_id, c.user_id, c.likes ๋ฅผ ๊ฐ์ง๊ณ ์ค๋๋ฐ, ์ถ๊ฐ๋ก
โ๏ธ Subquery ๐ checkins c2 ํ ์ด๋ธ ์์,
โ๏ธ where์ ๐ ์ ํด๋นํ๋ user_id๋ฅผ ๊ฐ์ง๊ณ ์๋ ์ ๋ค๋ง ๊ฐ์ ธ์์ค.
์ฌ์ค ์ด ๊ฒฝ์ฐ์๋ ๊ทธ๋ฅ group by ์ด์ฉํด์๋ ํ ์ ์๋ค.
select c.checkin_id,
c.user_id,
c.likes,
avg(likes) as avg_like_user
from checkins c
group by c.user_id
select ๋ฌธ์ subquery ๋ฃ๊ณ left join ๊น์ง ํ๋ ์์ .
select checkin_id,
c3.title,
user_id,
likes,
(
select avg(c2.likes) from checkins c2
where c.course_id = c2.course_id
)
from checkins c
left join courses c3 on c.course_id = c3.course_id;
select ๋ฌธ์ subquery ๋ฅผ ๋ฃ์ด์ฃผ๊ฒ ๋๋ฉด,
ํ์คํ์ค ์คํ๋ ๋ ๋ง๋ค, ๊ณ์ํด์ ๊ทธ ์์์๋ subquery ๊ฐ ๋์๊ฐ๊ฒ ๋๋ค.
from ์ ์์์ ์ฐ์ธ Subquery
๐ ์ด๋ฏธ ์๋ ํ ์ด๋ธ์ subquery๋ก ๋ง๋ ํ ์ด๋ธ์ join ํ๊ณ ์ถ์ ๋ ์ฌ์ฉ.
๐ ๋ด๊ฐ ์ถ์ถํ ๋ด์ฉ๋ง ๋ง์น ์ด๊ฒ๋ง ์๋ ํ ์ด๋ธ์ฒ๋ผ ์ธ ์ ์๋ค.
select pu.user_id, a.avg_like, pu.point from point_users pu
inner join (
select user_id, round(avg(likes),1) as avg_like from checkins
group by user_id
) a on pu.user_id = a.user_id
distinct( ํ๋ ์ด๋ฆ)
๐ ์ค๋ณต๋ ์์ ์ ๊ฑฐ.
๐ select ํ๋์ด๋ฆ, count(distinct(ํ๋์ด๋ฆ)) from ํ ์ด๋ธ
with table1 as ( ์๋ธ์ฟผ๋ฆฌ ), table2 as ( ์๋ธ์ฟผ๋ฆฌ)
๐ ์ค๋ณต๋ ์์ ์ ๊ฑฐ.
๐ select ํ๋์ด๋ฆ, count(distinct(ํ๋์ด๋ฆ)) from ํ ์ด๋ธ
๐ table ์ค๋ณตํด์ ์ค์ ํด ์ค ๋์๋ ์ฝค๋ง( , )๋ฅผ ์ด์ฉํ๋ค.
with table1 as
(
select c.course_id, count(distinct(c.user_id)) as cnt_checkins from checkins c
group by c.course_id
), table2 as (
select o.course_id, count(distinct(o.user_id)) as cnt_total from orders o
group by o.course_id
)
select c.title,
a.cnt_checkins,
b.cnt_total,
(a.cnt_checkins/b.cnt_total)as ratio
from table1 a
inner join table2 b on a.course_id = b.course_id
inner join courses c on b.course_id = c.course_id
'SQL' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
SQL DATEDIFF( ) / TIMESTAMPDIFF( ) / case when then else end (1) | 2023.09.24 |
---|---|
SQL ํ ์ด๋ธ ๋ถ์ด๊ธฐ inner join / left join / NULL (0) | 2023.09.23 |
sql ๊ธฐ์ด + group by / order by / where ์ค๋ณต (0) | 2023.09.23 |
SQL limit / distinct / count (0) | 2023.09.20 |
SQL where/ between and / like '%' / in() / != ์ด๊ฑฐ ์ ์ธํ๊ณ ๋ณด์ฌ์ค (0) | 2023.09.20 |