SQL 4주차_1

Drumj·2022년 2월 11일
0

SQL 정리

목록 보기
4/5

select u.user_id, u.name, u.email from users u
inner join orders o on u.user_id = o.user_id
where o.payment_method = 'kakaopay'
-- 이것을 서브쿼리를 이용해서 해보자!

SELECT user_id , name , email from users
where user_id in (
select user_id from orders o
where payment_method = 'kakaopay'
)
-- 쿼리문 안에 들어가는 쿼리문을 서브쿼리라고 부른다
-- 서브쿼리 먼저 결과를 만들고 밖의 쿼리를 수행한다
-- select / from / where 절에 모두 사용 할 수 있다

-- where 절에서 서브쿼리 사용하는 법
-- where 필드명 in (서브쿼리)

-- select절에 들어가는 서브쿼리
select c.checkin_id,
c.user_id,
c.likes,
(
select avg(likes) from checkins
-- 여기에는 checkins c 라고 쓰면 안된다
where user_id = c.user_id
) as avg_likes_user
from checkins c

-- from 절에 사용되는 서브쿼리 (가장 많이 사용됨)
select pu.user_id, pu.point, a.avg_likes from point_users pu
inner join(
select user_id, round(avg(likes),1) as avg_likes from checkins
group by user_id
) a on pu.user_id = a.user_id
order by pu.point desc

select * from point_users pu
where point > (
select round(avg(point),1) from point_users pu
)

select * from point_users pu
where pu.point > (
select avg(pu.point) from users u
inner join point_users pu on u.user_id = pu.user_id
where u.name ='이**'
)

select c.checkin_id,
c.course_id,
c.user_id,
c.likes,
(
select avg(likes) from checkins
where course_id = c.course_id
) as course_avg
from checkins c

select c.checkin_id,
c2.title,
c.user_id,
c.likes,
(
select round(avg(likes),1) from checkins
where course_id = c.course_id
) as course_avg
from checkins c
inner join courses c2 on c.course_id = c2.course_id
-- select 절에 서브쿼리를 사용해 보았다. 서브쿼리를 group by 로 묶어서 실패했다. where 절로 묶으니 성공했다. 연습이 필요할 듯

select c.title ,
a.cnt_checkins,
b.cnt_total,
(a.cnt_checkins/b.cnt_total) as ratio
from
(
select course_id , count(DISTINCT(user_id)) as cnt_checkins from checkins
group by course_id
) a
inner join
(
select course_id , COUNT(*) as cnt_total from orders
group by course_id
) b on a.course_id =b.course_id
inner join courses c on a.course_id = c.course_id
-- from절에 서브쿼리를 사용해 보았다. 사용은 괜찮았으나 한눈에 보기 아주 길어보인다. 헷갈릴 수 있을 것 같다.

-- 위의 from절 서브쿼리를 with 절을 이용해서 간편하게 바꿔보자!
with table1 as (
select course_id , count(DISTINCT(user_id)) as cnt_checkins from checkins
group by course_id
), table2 as (
select course_id , COUNT(*) as cnt_total from orders
group by 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 a.course_id = c.course_id

-- from안에 있는 서브 쿼리를 사용할때 with 절을 이용하면 굉장히 깔끔하게 쿼리를 작성할 수 있다!
-- 한 눈에 봐도 아주 깔끔해 보인다

0개의 댓글