스파르타코딩_SQL 문법 정리

Yunny
6 min readOct 21, 2022

--

  1. where
    -
    select * from orders
    where course_title = “앱개발 종합반”
    and payment_method = “kakaopay”;
    - and를 써서 조건을 여러 개 걸 수 있음
    - != ‘같지 않음’
    - 범위 between
    → select * from orders
    where created_at between “2020–07–13” and “2020–07–15”;
    - 포함 in
    → select * from checkins
    where week in (1, 3);
    - 패턴 like
    → select * from users
    where email like ‘%daum.net’
    → 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로 끝나는 모든 데 이터
  2. Group by, Order by
    - select 범주별로 세어주고 싶은 필드명, count(*) from 테이블명
    group by 범주별로 세어주고 싶은 필드명;
    - select 범주가 담긴 필드명, min(최솟값을 알고 싶은 필드명)
    from 테이블명 group by 범주가 담긴 필드명;
    → min, max, avg 등
    - select * from 테이블명 order by 정렬의 기준이 될 필드명;
    - select name, count(*) from users
    group by name
    order by count(*)
    → 내림차순은 order by count(*) desc
  3. Join(left, inner)
    - select * from users u
    inner join point_users p on u.user_id = p.user_id;
    - 네이버 이메일 사용하는 유저의 성씨별 주문건수 세어보기
    → select u.name, count(u.name) as count_name from orders o
    inner join users u on o.user_id = u.user_id
    where u.email like ‘%naver.com’
    group by u.name
  4. Union
    - select를 두 번 하지 않고 한 번에 보고 싶을 때
    → ( 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은 내부 정렬이 안 먹혀서 subquery 사용!
  5. Subquery
    -
    where 필드명 in (subquery)
    → Subquery의 결과를 조건에 활용하는 방식
    - select 필드명, 필드명, (subquery) from
    → 기존 테이블에 함께 보고싶은 통계 데이터를 손쉽게 붙이는 것
    - from subqeury
    → select pu.user_id, a.avg_like, pu.point from point_users pu
    inner join ( select user_id, round(avg(likes),1) as avg_like from checkins
    group by user_id ) a on pu.user_id = a.user_id
    →내가 만든 Select와 이미 있는 테이블을 Join하고 싶을 때
  6. with
    - 계속 서브쿼리가 붙으면, inner join 안쪽이 헷갈림
    - 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
  7. 문자열, case
    - SUBSTRING_INDEX

    → select user_id, email, SUBSTRING_INDEX(email, ‘@’, -1) from users
    → @를 기준으로 텍스트를 쪼개고, 그 중 마지막 조각을 가져오라는 뜻
    - SUBSTRING
    → SUBSTRING(문자열, 출력을 하고싶은 첫 글자의 위치, 몇개의 글자를 출력하고 싶은지)
    → select order_no, created_at, substring(created_at,1,10) as date from orders
    -case
    경우에 따라 원하는 값을 새 필드에 출력
    → select pu.point_user_id, pu.point,
    case
    when pu.point > 10000 then ‘잘 하고 있어요!’
    else ‘조금 더 달려주세요!’ END as ‘구분’
    from point_users pu;
    → with, subquery와 함께
    with table1 as ( select pu.point_user_id, pu.point,
    case
    when pu.point > 10000 then ‘1만 이상’
    when pu.point > 5000 then ‘5천 이상’
    else ‘5천 미만’
    END as lv
    from point_users pu )
    select level, count(*) as cnt from table1
    group by lv

--

--