[이미지 포함 정리 참고]
https://www.notion.so/d19236df3f2c4a72ad7845c47751b9c8?pvs=4
Joining Data in SQL
3. Set Theory for SQL Joins
Set Theory for SQL Joins
- Set : joining data 하는 새로운 방법
→ set theory에서의 벤다이어그램
- UNION : 두 테이블을 input으로 받고 두 테이블 모두에서 모든 records를 반환
- UNION ALL : union과 다르게 중복되는 records도 반환함.
- 계속 비슷한 형태로 사용됨. 앞선 joining과 다르게 on을 사용하지 않음. → stack fields one-another
- 두 테이블에 같은 수의 column이 있고 dtype가 같아야 error를 반환하지 않음(exercise)
→ prim_minister 호출했지만 출력 상에 나오지 않음-union은 leader와 prime_minister이 같은 사람이기 때문에 한 번만 호출/ norway에 딸린 사람은 다른 사람이기에 두 번 호출
At the INTERSECT
- INTERSECT : 두 테이블에 모두 있는 값만 리턴함.
→ 차이점 : 전자는 records를 비교하기 위해 column수 같아야 한다. 후자는 duplicate value를 return함.
EXCEPT
- EXCEPT : 차집합, left table-right table의 값만이 return
4. Subqueries
Subquerying with semi joins and anti joins
- Additive joins
- Semi join : second table의 조건과 맞는 첫 번째 테이블에 있는 records를 고름.
- building on our semi join
: second table의 조건과 맞지 않은 first 테이블의 reocrd를 찾음.
Subqueries inside WHERE and SELECT
- Syntax for subqueries inside WHERE : subqueries에서 where 가장 중요하게 사용됨 → filtering이 데이터 조작에서 중요한 역할을 하기 때문
→ some_field 와 some_numeric_field dtype이 같아야 에러 발생x
- Subqueries inside SELECT : 같은 table 안에서만 사용 가능한 group by와 유사한 개념
Data Manipulation in SQL
1. We’ll take the case
We’ll take the CASE
- case를 사용해 data manipulation을 하는 방법을 배움
- selecting, filtering, grouping data, joining data → 사전지식 요구
- Selecting from the European Soccer Database
CASE statements : WHEN, THEN, ELSE statement를 포함하며 END로 끝나고 Alias가 할당.
→ 완성된 CASE statement는 하나의 column을 평가
In CASE things get more complex
→ 다수의 logical conditions의 경우 CASE에 AND를 추가
- What ELSE is being excluded?
WHERE OR 구문을 추가해서 첼시 팀이 홈 경기거나 away team 경기인 경우만을 표기
→ 똑같은 결과를 도출
- Where to place your CASE? : WHERE 안에 case 구문을 넣어둠.
CASE WHEN with aggregate functions
- CASE : categorizing data, filtering data, aggregating data에 유용
- CASE WHEN with COUNT/ AVG에서도 같은 방법
- A ROUNDed AVG : ROUND(num, k) : k자리까지 반올림
- Percentages with CASE and AVG
2. Short and Simple Subqueries
WHERE are the Subqueries?
- subquery : a query nested inside another query
→ 매개자 transformation에 유용
→ 어느 query에도 들어갈 수 있다. ex) SELECT, FROM, WHERE, GROUP BY
→ 다양한 종류의 정보를 return함 : scalar, a list, a table ..
- Why subqueries ?
- summarized values에 대해 그룹 간의 비교를 가능하게 함.
- data reshaping 가능하게 함.
- join 될 수 없는 데이터를 결합함.
- Simple subqueries : outer query와 독립적으로 평가 가능함.
→ 전체 statement에서 한 번만 진행됨.
- Subqueries in the WHERE clause
- Subquery filtering list with IN
Subqueries in FROM
- restructure and transform your data
- Transforming data form long to wide before selecting
- prefiltering data
- Calculating aggregates of aggregates
Subqueries in SELECT :
→ how much higher than the average
- Subqueries in SELECT : 예제
- SELECT subqueries for mathematical calculations
→ 많은 시간과 error를 줄여줄 수 있음.
- 주의사항 :
- single value를 반환해야 함. : 데이터 셋의 each row에 작용하기 때문에
- have all filters in the right place
Subqueries everywhere! And best practices!
- As many subqueries as you want : where, select, from 등 여러 곳에서 사용 가능 함
- Format your queries : SELECT., FROM, WHERE, GROUP BY
- Annotate your queries : 주석을 통해 설명
→ /* */ or - - 사용 가능
- Indent your subqueries : 이해에 도움을 줌
clearly indent ! → Hollywell’s SQL style guide 참조
- Is that subquery necessary ?
→ subquery는 computing power 필요로 하기에 꼭 필요한 것인지를 고려하기!
-Proper filter subqueries ; 여러 위치해서 같은 filter 나올 수 있음
댓글 영역