[sql][스파르타] 3주차-2 left join

Regina·2022년 10월 27일
0

SQL

목록 보기
7/9
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

inner join을 두 번 걸 수 있다.
첫번째는 c와 c2에서 course_id를 키로 join
두번째는 c2와 o에서 user_id를 키로 join

헷갈리는 것, 실수하는 것

1) 포함인지 아닌지. = 를 써야하는지 아닌지
2020년 8월 1일 이후니까 8월 1일도 포함해서 >=
2) where 조건문에서 날짜 범위 적을때
자꾸 where 조건문 날짜 할때 '~' 따옴표를 안 적는 실수 하지 말기!!
날짜도 ' '로 적어야 함.

left join

null 값을 포함해서 통계를 내거나 해야 할 때 left join을 쓰면 되겠죠.

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

null 값인 것을 조건문으로 걸때는 ~ is NULL 로 해줘야 함
반대는 ~ is not NULL 로 해줌

+) count 는 null 인 데이터는 세지 않음. null 인 건 자동으로 빼고 센다는 뜻.

예제 연습하다가 질문 남겼던 것

sql에서의 alias 는 다른 프로그래밍 언어의 변수처럼 사용할 수는 없음. select 에서 변수처럼 사용할 수 없음. group by나 order by 같이 특정 기능을 할 때 별칭을 사용할 수는 있음.
해당 alias 가 고정적으로 사용된다면 view 기능을 이용해서 사용하는 방법이 있음.

튜터님 답변

sql 에서의 별칭은 프로그래밍에서의 변수처럼 값을 저장할 수 있는 기능이 없기 때문에 질문해주신 내용처럼 사용은 불가합니다.

union

7월과 8월 데이터를 합치기

8월로 다 입력된 month 열 만들기

select '8월' as month, 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

'8월' as month 라고 쓰면 됨.

(
	select '7월' as month, 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
)

union ALL 

(
	select '8월' as month, 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
)

보기 좋게 괄호 안은 tap 으로 들여쓰기를 해줌
그런데 union all 을 하면 order by 해줬던 게 안 먹음. 전체를 합친 다음에 그때 다시 정렬을 해줘야 하는데 그건 이제 다음 시간에 정리하겠음.

profile
하루하루 더 나은 사람이 되어보자

0개의 댓글