SQL - 4주차(Subquery, With절)

최문성·2021년 12월 23일
0

SQL 강의내용 정리

목록 보기
4/4
post-thumbnail

1). Subquery 의미

: 쿼리 안의 쿼리가 들어 있다는 뜻

하위 쿼리의 결과를 상위 쿼리에서 사용하면, SQL 쿼리가 훨씬 간단해진다

< 아래 예시 - 쿼리문 내부에 쿼리문 >

select u.user_id, u.name, u.email from users u
where u.user_id in (
	select user_id from orders
	where payment_method = 'kakaopay'
)
  • 함께 자주 쓰이는 문법
    : Where, Select, From

    1). Where ~
    Q. 전체 유저의 포인트의 평균보다 큰 유저들의 데이터 추출하기

select * from point_users pu 
where pu.point > (select avg(pu2.point) from point_users pu2);

2). Select ~
Q. checkins 테이블에 course_id별 평균 likes수 필드 우측에 붙여보기

select checkin_id, course_id, user_id, likes, 
(select avg(c2.likes) from checkins c2
where c.course_id = c2.course_id) 
from checkins c;

3). From ~
Q. course_id별 유저의 체크인 개수를 구해보기

select course_id, count(distinct(user_id)) as cnt_checkins from checkins
group by course_id

2). With 절

: with 절로 더 깔끔하게 쿼리문을 정리하기

Q. 코스제목별 like 개수, 전체, 비율 구하기

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
profile
코딩하는 마케터로 거듭나기

0개의 댓글