엑셀보다 쉬운 SQL - 3주차(Join)

dlfpire·2023년 3월 29일
0

스파르타코딩클럽

목록 보기
3/4
select * from AT a
inner join BT b on a.x = b.x

=> 위 쿼리가 실행되는 순서 : from - join - select

: 왼쪽에 붙임
겹치는 필드 (x)가 있는 두 테이블을 합침
-> AT 테이블에는 있지만 BT 테이블에는 없는 것도 모두 한 테이블에 나옴
-> 어떤 데이터는 모든 필드가 채워져있지만, 어떤 데이터는 비어있는 필드가 있을 수 있음

  • 꽉찬 데이터 : 해당 데이터의 x 필드값이 BT 테이블에 존재해서 AT 테이블에 연결한 경우

  • 비어있는 데이터 : 해당 데이터의 x 필드값이 BT 테이블에 존재하지 않는 경우

    A에 B를 붙인다. 순서가 굉장히 중요함!

: 교집합
-> 겹치는 필드가 있는 데이터들만 나옴

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

👉🏻 위 쿼리가 실행되는 순서 : from - join - where - group by - select

<퀴즈>

  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
  1. 결제하고 시작하지 않은 유저들을 성씨별로 세어보기
select u.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 u.name
ORDER by count(*) desc
  1. 과목 별로 시작하지 않은 유저들을 세어보기
select c.course_id, c.title, count(*) as cnt_notstart from courses c
inner join enrolleds e on c.course_id = e.course_id
where e.is_registered = 0
group by c.course_id
  1. 웹개발, 앱개발 종합반의 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
  1. 4번 퀴즈에서 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
  1. 7/10~7/19 에 가입한 고객 중,
    포인트를 가진 고객의 숫자, 그리고 전체 숫자, 그리고 비율 보기
select count(pu.point_user_id) as pnt_user_cnt,
   	   count(*) as tot_user_cnt,
   	   round(count(pu.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'

0개의 댓글