상세 컨텐츠

본문 제목

SQL inner join 연습

코딩/SQL

by joing_in 2023. 3. 15. 18:05

본문

[실습] orders 테이블에 users 테이블 연결해보기

ex)

SELECT * from orders o

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

 

[실습] checkins 테이블에 users 테이블 연결해보기

ex)

SELECT * from checkins c

inner join users u on c.user_id = u.user_id

 

[실습] enrolleds 테이블에 courses 테이블 연결해보기

ex)

SELECT * from enrolleds e

inner join courses c on e.course_id = c.course_id

 

checkins 테이블에 courses 테이블 연결해서 통계치 내보기

(과목별 오늘의 다짐 갯수 세어보기)

ex)

SELECT c1.course_id, count(*) as cnt from checkins c1

inner join courses c2 on c1.course_id = c2.course_id

group by c1.course_id

 

point_users 테이블에 users 테이블 연결해서 순서대로 정렬해보기

(많은 포인트를 얻은 순서대로 유저 데이터 정렬해서 보기)

ex)

SELECT * from point_users p

inner join users u on p.user_id = u.user_id

order by p.point desc

 

깔끔하게 보기

ex)

SELECT p.user_id, u.name, u.email, p.point from point_users p

inner join users u on p.user_id = u.user_id

order by p.point desc

 

orders 테이블에 users 테이블 연결해서 통계치 내보기

(네이버 이메일 사용하는 유저의 성씨별 주문건수 세어보기)

ex)

SELECT u.name, COUNT(*) 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

 

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

ex)

SELECT o.payment_method, round(avg(pu.point),0) as avg_point from point_users pu

inner join orders o on pu.user_id = o.user_id

group by o.payment_method

 

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

ex)

SELECT u.name, count(*) as cnt_name from enrolleds e

inner join users u on e.user_id = u.user_id

where e.is_registered = 0

group by u.name

order by count(*) desc

 

[퀴즈]과목 별로 시작하지 않은 유저들을 세어보기

ex)

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

 

** course_id 사용해도 되는 이유

데이터 행의 갯수를 세면 되기 때문에, 유저를 세어보는 것이므로 굳이 user_id를 사용하지 않아도 된다.

 

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

ex)

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

 

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

ex)

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

 

** course_id를 사용하지 않고 user_id를 사용하는 이유

알고자하는 게 해당 날짜 이후 구매한 '고객'이기 때문에 강의를 선별해주는 course_id가 아닌 order테이블에 있는 user_id를 사용한 것이다 

'코딩 > SQL' 카테고리의 다른 글

SQL Union, Subquery  (0) 2023.03.17
SQL left join 연습  (0) 2023.03.17
SQL join, Alias  (0) 2023.03.15
SQL Group by, Order by 연습  (0) 2023.03.15
SQL Order by  (0) 2023.03.15

관련글 더보기