본문 바로가기

A.개발관련자료

[0][sql]스파르타sql 정리

//field : table 의 특정 분류값 

//1주차 정리
1.show tables (cmd + enter : 실행) 로 필드 값 확인
2.select * from TableName 
3. where fieldName = '조건' and/or '조건'

*조건 : (문자열이 아닐경우 table이나 field로 인식함)
*사칙연산 조건 : != (제외하고)
*범위 조건 : between DATE and DATE
*포함 조건 : where fieldName in (숫자들)
*패턴 조건:
-특정string을 포함하는 => where fieldName like '%특정string%'
-규칙적인 string을 포함하는 =>ex) where fieldName = '김**'
* 몇줄만 보고 싶을때 : limit 
*중복 제외+count :  ex) select count(distinct(payment)) from orders
//2주차 정리 - 통계 (최대, 최소, 평균, 갯수, groupby, orderby)

1.where groupby(분류별) orderby 순서로 작성
2.groupby - min, max, avg, round(숫자,n자리까지),sum
3.order by filedA ASC/DESC (string, number, date 다 가능), fieldB ASC/DESC
- A순 차순정리 후 B순 차순정리
4.Alias(별칭) - 필드명 as aliasName / table aliasName
//3주차 정리 - left join, inner join, union
1. select * from tableName A
left join / inner join tableName2 B on A.특정필드   = B.특정필드 
left join / inner join tableName3 C on A.특정필드 = C.특정필드
2.inner join (교집합) - null 제외
/left join(왼쪽인 A 에 붙이기:순서가 중요) - 없으면 null  
3. left join(없는값 =null의 통계낼때 주로 사용)
-join table에서 null 빼기 => where fieldName is NULL / is not NULL 
 *count => null 이 아닌것만 count 함
4.union all : 두 table을 하단으로 이어주는 명령어
(select~) union all (select~) order by ~
* union 내부에서는 order by가 안먹음 =>union all 후 외부에서 실행
//4주차 정리 - subquery, with구문(subquery 간결), case when
1.서브쿼리 먼저 실행후 바깥 조건문을 생성 
-where절, select절,from절에 대입 가능 
2. where 절 : where 필드명 in (select 서브쿼리)
3. select절 : select 필드명, 필드명, subquery절  => 특정 필드명의 조건이 필요할때
4. from절 : select ~ from tableA inner join (subquery B) abc on A.필드 = abc.필드
-방금 만든 select문을 마치 원래 있던 테이블처럼 사용
-join 잘되었는지 확인하려면, select 필드명, 필드명,abc.*(join 완료된 전체 테이블 abc를 보여줘)로 확인
-from에 들어갈 테이블 먼저 작성 => inner join으로 묶기 =>전체 테이블 확인후 alias 필드명 수정
5. with절 : from 절 서브쿼리를 간단히 볼수 있음

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

ex2)
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
//5.실전에서 유용한 sql - 문자열데이터 정리 , 조건문별 데이터(case when)
1. 문자열 데이터를 원하는 형태로 정리 -substring_index/substring
abc@hanmail.com  =>substring_index(email,'@',-1) => email을 @기준으로 마지막 것만 보여줘 (hanmail.com)
2020-07-01 22:30:49 => substring(created_at,1,10) => createdat을 1~10자 사이로 잘라줘 (2020-07-01)
2. (case when a.point > 10000 then '1만이상' when a.point > 5000 then '5천이상 ' else '5천미만' end) as aliasName