개발일지

4주차 SQL 과제 본문

강의/SQL

4주차 SQL 과제

MotherCarGasoline 2022. 2. 21. 23:02

- where

1) 같지않음 !=

2) 범위

select * from orders
where created_at between "2020-07-13" and "2020-07-15";

3) 포함

select * from checkins 
where week in (1, 3);

4) 패턴

select * from users 
where email like '%daum.net';

👉 Like는 패턴으로 조건을 거는 문법으로, 사용법이 아주 다양하답니다!

  • where email like 'a%': email 필드값이 a로 시작하는 모든 데이터
  • where email like '%a' email 필드값이 a로 끝나는 모든 데이터
  • where email like '%co%' email 필드값에 co를 포함하는 모든 데이터
  • where email like 'a%o' email 필드값이 a로 시작하고 o로 끝나는 모든 데이터

👉 이외에도 여러 문법이 있는데, 그때그때 필요한 것을 찾아서 쓰면 됩니다! 같이 한번 찾아볼까요? ('how to use like in sql' 구글링!)

 

5) Limit 일부데이터만 가져오기

select * from orders 
where payment_method = "kakaopay"
limit 5;

6) Distinct중복데이터 제거하고 가져오기

select distinct(payment_method) from orders;

count 같이 쓰기

SELECT count(distinct(name)) from users;

 

- group by  범주의 통계를 내주는

select name, count(*) from users
group by name;

 

동일한 범주의 개수 count, 최솟값 min, 최댓값 max, 평균 avg, 합계 sum

 

- order by 깔끔한 정렬이 필요할땐

select * from 테이블명
order by 정렬의 기준이 될 필드명;

- 별칭 기능: Alias

 

- join 

select * from enrolleds e
inner join courses c
on e.course_id = c.course_id;

👉 위 쿼리가 실행되는 순서: from → join → select

from enrolleds: enrolleds 테이블 데이터 전체를 가져옵니다.

  1. inner join courses on e.course_id = c.course_id: courses를 enrolleds 테이블에 붙이는데, enrolleds 테이블의 course_id와 동일한 course_id를 갖는 courses의 테이블을 붙입니다.
  2. select * : 붙여진 모든 데이터를 출력합니다.

👉 항상 from에 들어간 테이블을 기준으로, 다른 테이블이 붙는다고 생각하면 편합니다!

    - subquery

👉 Subquery란? 쿼리 안의 쿼리라는 의미입니다.

하위 쿼리의 결과를 상위 쿼리에서 사용하면, SQL 쿼리가 훨씬 간단해져요!

  • kakaopay로 결제한 유저들의 정보 보기
    select u.user_id, u.name, u.email from users u
    inner join orders o on u.user_id = o.user_id
    where o.payment_method = 'kakaopay'
    
  • → 우선, 이렇게 볼 수 있겠죠? users 와 orders 의 inner join으로!
  • 그런데, 이것을 이렇게 할 수도 있습니다. 조금 더 직관적이지 않나요?
    1. 우선 kakaopay로 결제한 user_id를 모두 구해보기 → K 라고 합시다.
    select user_id from orders
    where payment_method = 'kakaopay'
    
    → 이게 바로 서브쿼리!     
      2. 그 후에, user_id가 K 에 있는 유저들만 골라보기
  • select u.user_id, u.name, u.email from users u
    where u.user_id in (
    	select user_id from orders
    	where payment_method = 'kakaopay'
    )
    

- with

select c.title,
       a.cnt_checkins,
       b.cnt_total,
       (a.cnt_checkins/b.cnt_total) as ratio
from
(
	select course_id, count(distinct(user_id)) as cnt_checkins from checkins
	group by course_id
) a
inner join
(
	select course_id, count(*) as cnt_total from orders
	group by course_id 
) b on a.course_id = b.course_id
inner join courses c on a.course_id = c.course_id

이렇게 계속 서브쿼리가 붙으면, inner join 안쪽이 너무 헷갈리겠죠!

→ 그 때 쓰는 것이 with 절! 결과는 같은데 훨씬 보기가 좋죠?

with table1 as (
	select course_id, count(distinct(user_id)) as cnt_checkins from checkins
	group by course_id
), table2 as (
	select course_id, count(*) as cnt_total from orders
	group by course_id
)

select c.title,
       a.cnt_checkins,
       b.cnt_total,
       (a.cnt_checkins/b.cnt_total) as ratio
from table1 a inner join table2 b on a.course_id = b.course_id
inner join courses c on a.course_id = c.course_id

- 문자열 데이터 ( 이메일, 날짜 출력)

                             2020-07-13 22:00:41  

 

- case

'강의 > SQL' 카테고리의 다른 글

3주차 SQL 과제  (0) 2022.02.20
2주차 SQL 과제  (0) 2022.02.17
1주차 개발일지 쓰기  (0) 2022.02.17
Comments