SQL 3주차

김은지·2023년 1월 29일
0

[3주차 개발일지 시작 ^_^] - join & union

join
-연결의 기준이 되고 싶은 테이블을 from절에
붙이고 싶은 테이블을 join절에 놓기
-두 테이블의 공통된 값 = key값

-쿼리실행순서 : from - join - where - group by - select - order by
(join의 실행순서는 from과 항상 함께 다닌다,
order by 맨마지막!)

join예제) 네이버 이메일을 사용하는 유저의 성씨별 주문건수 세어보기
(orders 테이블에 users 테이블 연결해서 통계치 내기)

select u.name, count(u.name) as cnt from orders o
inner join users u 
on o.user_id = u.user_id
where u.email like '%naver.com'
group by u.name

join연습1) 결제수단 별 유저 포인트의 평균값 구해보기

select o.payment_method,round(avg(pu.point)) as avg_point 
from point_users pu 
inner join orders o 
on pu.user_id = o.user_id 
group by o.payment_method

join연습2) 결제하고 시작하지 않은 유저들을 성씨별로 세어보기( 어느 성이 가장 시작을 안하였는가~)

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

join연습3) 과목 별로 시작하지 않은 유저들 세어보기

select c.title, count(*) as cnt from enrolleds e
inner join courses c 
on e.course_id = c.course_id
where e.is_registered = 0
group by c.title

*위 쿼리에서 courses 에 enrolleds 붙여도(순서바꿔도) 동일결과 나옴.

join연습4) 웹개발, 앱개발 종합반의 week별 체크인 수 세고, 보기 좋게 정리하기

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

join연습5) 연습4번에서 8월 1일 이후에 구매한 고객들만 발라내기
(꼭 다시 풀어보기. orders 테이블 join시 키값, 8/1이후 구매할 때 '>=' 등호 붙이기 주의)

select c.title, c2.week, count(*) as cnt from courses c 
inner join checkins c2 on c.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 c.title, c2.week 
order by c.title, c2.week

left join 주의사항, 기능
1) 어디에 뭐를 붙일건지, 순서가 중요
2) count에서 null은 세지 않는다
3) users - point_users left join연결 시,
유저 중에 포인트가 없는 사람(시작하지 않은 사람)의 통계 가능 ( " is null " , " is not null " 사용해보기 )

select u.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 u.name

union - 결과물 합치기
select 를 두번할 게 아니라 한번에 모아서 보고싶은 경우
1) 단, 합칠 2가지의 필드명이 같아야 한다
2) order by 가 깨진다

union연습1) 웹개발, 앱개발 종합반의 week별 체크인 수,
7월과 8월 결과 합쳐서 보기

(
	select '7월' as month, c.title, c2.week, count(*) as cnt from courses c 
	inner join checkins c2  on c.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 c.title, c2.week 
	order by c.title, c2.week
)
union ALL 
( 
	select '8월' as month, c.title, c2.week, count(*) as cnt from courses c 
	inner join checkins c2  on c.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 c.title, c2.week 
	order by c.title, c2.week
)
profile
데이터분석, SQL

0개의 댓글