본문 바로가기

Sparta coding club_SQL

[엑셀보다 쉬운 SQL] 3주차 _Join_테이블을 연결해보자

원하는 데이터를 출력하고 싶은데, 두 테이블에 데이터가 나눠져 있을 때!

Join을 사용해서 테이블을 붙일 수 있습니다.

다만 동일한 이름의 필드가 있어야 합니다.

 


 

Join 이란

두 테이블의 공통된 key 값을 기준으로 연결하여 한 테이블처럼 보는 것. 엑셀의 vlookup 함수와 동일한 기능

  • Left Join : 왼쪽 테이블에 다른 하나의 테이블을 붙인다고 생각하기. 테이블 A와 테이블 B의 공통된 key 값을 통해 연결합니다.
  • Inner Join : 테이블 A와 테이블 B의 교집합. 양 테이블에서 모두 가지고 있는 데이터만 출력하기 때문에 빈칸의 필드가 존재하지 않습니다. 
  •  

Q) 결제수단 별 유저 포인트의 평균값 구하기

- Join 할 테이블 : point_users, orders

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

on 다음 두 테이블의 key값을 일치시켜 줍니다. 

 

 

데이터가 없는 빈칸을 출력 또는 제외시키기

is NULL / is not 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

 

 

count는 NULL을 세지 않습니다!

Left Join 사용 시, count를 통해 빈칸의 개수, total 개수를 출력하고 이에 따른 비율 ratio를 출력할 수 있습니다.

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

Union을 사용하여 결과물을 합칠 수 있습니다. 다만 동일한 필드명을 갖고 있어야 합니다.

(
	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
)

union을 사용하면 order by를 통한 내부정렬이 작동하지 않습니다. 이는 서브쿼리를 통해 해결할 수 있습니다.