스파르타 코딩클럽 - SQL 3주차

박민영·2023년 3월 30일
0

엑셀보다 쉬운 SQL

목록 보기
3/4
post-thumbnail

join

두 테이블을 공통된 필드를 기준으로 연결해서 한 테이블로 묶는 것.

inner join

a, b 테이블의 교집합, 즉 두 테이블에서 모두 가지고 있는 데이터만 출력됨

select * from orders o

inner join users u
on o.user_id = u.user_id;

별칭(alias) 꼭 붙이기

연결의 기준이 되고싶은 테이블을 from 절에,

기준이 되는 테이블에 붙이고 싶은 테이블을 Join 절에 위치해 놓습니다.

select u.name, count(u.name) as count_name from orders o

inner join users u
on o.user_id = u.user_id
where u.email like '%naver.com'
group by u.name

where절 붙이고 group by 붙이기

결제 수단 별 유저 포인트의 평균값 구해보기

select o.payment_method, round(AVG(p.point)) from point_users p
inner join orders o
on p.user_id = o.user_id
group by o.payment_method

결제하고 시작하지 않은 유저들을 성씨별로 세어보기

select name, count(*) as cnt_name from enrolleds e
inner join users u
on e.user_id = u.user_id
where is_registered = 0
group by name
order by cnt_name desc

웹개발, 앱개발 종합반의 week 별 체크인 수를 세어볼까요? 보기 좋게 정리해보기!

select c1.title, c2.week, count(*) as cnt from checkins c2
inner join courses c1 on c2.course_id = c1.course_id
group by c1.title, c2.week
order by c1.title, c2.week

group by로 묶을 게 여러가지 일 경우 ',' 붙이기

연습4번에서, 8월 1일 이후에 구매한 고객들만 발라내어 보세요!

select c1.title, c2.week, count(*) as cnt from courses c1
inner join checkins c2 on c1.course_id = c2.course_id
inner join orders o on c2.user_id = o.user_id
where o.created_at >= '2020-08-01'
group by c1.title, c2.week
order by c1.title, c2.week

left join

b테이블을 a 테이블에 붙이는 것. 데이터가 비어있을 경우 'null'로 뜬다.

유저 중에, 포인트가 없는 사람(=즉, 시작하지 않은 사람들)의 통계!

select name, count(*) from users u
left join point_users pu on u.user_id = pu.user_id
where pu.point_user_id is NULL
group by name

유저 중에, 포인트가 있는 사람(=즉, 시작한 사람들)의 통계!

select name, count(*) from users u
left join point_users pu on u.user_id = pu.user_id
where pu.point_user_id is not NULL

7월10일 ~ 7월19일에 가입한 고객 중,

포인트를 가진 고객의 숫자, 그리고 전체 숫자, 그리고 비율을 보고 싶어요!

select count(point_user_id) as pnt_user_cnt,
count() as tot_user_cnt,
round(count(point_user_id)/count(
),2) as ratio
from users u
left join point_users pu on u.user_id = pu.user_id
where u.created_at between '2020-07-10' and '2020-07-20'

union

결과물(select)들을 한번에 모아서 보고 싶을 때
대신 내부 order by가 적용되지 않음

(

select '7월' as month, c.title, c2.week, count(*) as cnt from checkins c2
inner join courses c on c2.course_id = c.course_id
inner join orders o on o.user_id = c2.user_id
where o.created_at < '2020-08-01'
group by c2.course_id, c2.week

order by c2.course_id, c2.week
)
union all
(
select '8월' as month, c.title, c2.week, count(*) as cnt from checkins c2
inner join courses c on c2.course_id = c.course_id
inner join orders o on o.user_id = c2.user_id
where o.created_at >= '2020-08-01'
group by c2.course_id, c2.week
order by c2.course_id, c2.week
)

숙제

SELECT e.enrolled_id ,e.user_id , COUNT(*) as cnt FROM enrolleds e
inner join enrolleds_detail ed on e.enrolled_id = ed.enrolled_id
where ed.done = 1
group by e.enrolled_id, e.user_id
order by cnt desc

profile
개발자로 취뽀하기!!

0개의 댓글