SQL Course
SQL Course
A database is an organized
collection of data whose content
must be quickly and easily
• Logical: Construct a model of the data using a specific model, but without consideration for the
actual database system that will eventually store the data and run the application.
• Physical: Design a model for implementing the logical model that considers the RDBMS to be
used. During this phase, you’ll describe tables, indexes, and so on. The physical model is built on
tables.
Database schema & database state
• A database schema or an intention gives a description of the database. This
can be considered as a blueprint of a database and gives a list of fields in the
database with their data types. In other words, it describes the organization
and structure of data in a database system, along with the relationships
mapped between the entities.
• A database state provides the present state of the database and its data. It
can be considered as an extension of the database schema. When a
database is newly defined, the corresponding database state is empty.
Factors that affect a database state are entering, deleting or modifying
information in the database.
Example of Database Schema
Example of Database State
WHAT IS DATABASE MANAGEMENT SYSTEM?
The database management system (DBMS) is the software that interacts
with end users, applications, and the database itself to capture and
analyze the data.
The DBMS software additionally encompasses the core facilities
provided to administer the database.
The sum total of the database, the DBMS and the associated
applications can be referred to as a "database system".
Often the term "database" is also used to loosely refer to any of the
DBMS, the database system or an application associated with the
database.
DBMS Languages
DMS RDMS
Normalization
• Remove redundancies.
• eliminate redundant data (for example, storing the same data in
more than one table) and
Examples of Normalization
1 Coca #Cl1 Red #Br1 Cocaco 293 F&B 101020 Kan 102 Mono #1288 12023033 12 HCM
Thung la
2 Bia Tiger #Cl1 Blue #Br1 Tiger 293 F&B 292922 Huy 102 Mono #1288 12023033 12 HCM
1 Coca #Cl1 Red #Br1 Cocaco 293 F&B 101020 Kan 102 Mono #1288 12023033 12 HCM
Thung la
PID PNAME ColorID Brand ID Cust No Cust Name Payment Payment Store Id Store Cate Id Cate Name
Id Name Name
293 Food &
1 Coca #Cl1 #Br1 101020 Kan 102 Mono 12 HCM Bevarage
Thung
293 Food &
2 Bia Tiger #Cl1 #Br1 292922 Huy 102 Mono 12 HCM Bevarage
1 Coca #Cl1 #Br1 101020 Kan 102 Mono 12 HCM 293 Food &
Thung Bevarage
#Br1 Cocacola pname = ‘Coca’ and cust_name = 1 293 10102 102 #1288 12023033 12
#Cl1 Red
‘Huy’ and payment_name = ‘momo’ 2 293 29292 102 #1288 12023033 12
#Cl1 Blue #Br1 Tiger
and color =‘red’ and brand = ‘Tiger’
#Cl1 Red #Br1 Cocacola and store = ‘hcm’ 1 293 10102 102 #1288 12023033 12
Denormalize the Normalized Databases
Using pre-joined tables
Example
All users have 2 storage “message” and
“file” to keep their data.
Denormalize the Normalized Databases
Adding short-circuit keys
Benefits: Now we can have infinite phone numbers or company addresses for
each contact
Drawback: Now we have to type in everything over and over again. This leads to
inconsistency, redundancy and wasting space. Thus, the second normal form
Second Form
• Create separate tables for sets
of values that apply to multiple
records.
•
-
-
-
-
-
-
•
•
IS A SYSTEM INCLUDING PROCESS, TECH, DATA PRESENTATIONS
DATA WAREHOUSE DEFINITION
- HV biết các tạo data set, upload cơ sở dữ liệu vào data warehouse
- Bảng và các kiểu dữ liệu chính trong SQL
- Chọn vùng dữ liệu
- Các chức năng saved queries, query history, save result
- Lọc dữ liệu với WHERE
Syntax conventions
• Upper or Lower insensitive
• Write keyword Upper case letters
• White-space insensitive
• Use ; for terminator
ĐĂNG NHẬP VÀO
BIGQUERY UI
BẮT ĐẦU SỬ DỤNG BIGQUERY
● Step 1: Truy cập vào trang web:
https://console.cloud.google.com/bigquery?project và chọn Đặng nhập
BẮT ĐẦU SỬ DỤNG BIGQUERY
● Step 2: Đăng nhập bằng tài khoản Google
BẮT ĐẦU SỬ DỤNG BIGQUERY
● Sau đó bạn sẽ được dẫn và BigQuery UI
TẠO PROJECT VÀ
THÊM DATASET
Tạo Project
TẠO PROJECT
- Step 1: Trong giao diện BigQury UI, chọn vào phần chọn project
- Step 2: Chọn New Project
TẠO PROJECT
- Step 3: Đặt tên cho Project và
chọn Create
Thêm Dataset
vào Project
Thêm Dataset vào Project
- Step 1: Trong cửa sổ BigQuery UI, chọn project muốn tạo dataset
- Step 2: Chọn Create Dataset
Thêm Dataset vào Project
- Step 3: Điền tên cho project
- Step 4: Chọn location cho project
BẢNG VÀ CÁC KIỂU DỮ
LIỆU
TẠO TABLE
- Step 1: Trong giao diện BigQuery UI, chọn project, sau đó chọn dataset muốn thêm
bảng vào.
- Step 2: Chọn New Project
TẠO PROJECT
- Step 3: Điền thông tin của bảng, chi
tiết cột trong bảng. Sau đó nhấn
Create Table
Date / time DATETIME Giá trị ngày, tháng, năm, 2020-02-25 16:59:50
giờ, phút, giây theo format:
YYYY-(M)M-(D)D
(H)H:(Mi)Mi:(S)S
Ở ví dụ bên phải,
mình chọn tất cả
các cột từ bảng
data_test
Chọn dữ liệu từ tất cả
cột ngoại trừ...
CHỌN DỮ LIỆU TỪ MỘT HOẶC NHIỀU CỘT
Để chọn dữ liệu từ bảng ngoại trừ các cột tuỳ chọn ta dùng syntax:
- Đối với dữ liệu dạng boolean, giá trị dữ liệu có dạng true hoặc false vì vậy câu lệnh lọc có 2
dạng phổ biến:
và
-Để thuận tiện cho việc lọc ta nên sử dụng hàm LOWER() để chuyển các giá trị trong cột lọc về chữ
thường. Ví dụ như:
SELECT COUNT(column_name)
FROM ‘table_name’
SELECT COUNT(*)
FROM ‘table_name’
ĐẾM SỐ LƯỢNG GIÁ TRỊ TRONG CỘT
Để đếm số lượng các giá trị riêng biệt trong 1 cột,
ta sử dụng thêm điều kiện DISTINCT vào câu lệnh
COUNT() theo mẫu sau:
FROM ‘table_name’
SELECT DISTINCT column_name Ở ví dụ trên ta có thể thấy có tổng cộng 23 dòng trong
cột InvoiceNo tuy nhiên chỉ có 4 giá trị riêng biệt.
FROM ‘table_name’
HÀM TÍNH TỔNG
Để tính tổng của những giá trị trong 1
cột, ta sử dụng câu lệnh SUM() theo
mẫu sau:
SELECT SUM(column_name)
FROM ‘table_name’
HÀM TÍNH TRUNG BÌNH
Để tính trung bình của những giá trị
trong 1 cột, ta sử dụng câu lệnhAVG()
theo mẫu sau:
SELECTAVG(column_name)
FROM ‘table_name’
HÀM LẤY GIÁ TRỊ NHỎ NHẤT VÀ LỚNNHẤT
SELECT MIN(column_name)
FROM ‘table_name’
SELECT MAX(column_name)
FROM ‘table_name’
HÀM LẤY PHƯƠNG SAI VÀ ĐỘ LỆCH CHUẨN
SELECT VAR_POP(column_name)
FROM ‘table_name’
SELECT STDDEV_POP(column_name)
FROM ‘table_name’
Subquery
Subquery (Truy vấn con)
1. Sử dụng bảng GA_02, chọn ra Campaign_ads_ID không phải là 1917939744 và 1917978903, có Campaign_ads_name là
‘wolf’, có Impressions nằm trong khoảng 500 - 1000.
2. SD GA_02M, lấy ra những project sau: Cassandra hoặc LA Bee One hoặc Galinburg, có Ad type là Image Ad hoặc
Expanded text ad, có Date trong khoảng 2019-06-01 đến 2019-07-03, Có CR lớn hơn 0.15. Sắp xếp theo thứ tự giảm dần
của Cost.
3. Báo cáo hiệu quả của project thông qua các chỉ số Cost, Impressions, Clicks, Conversions, Video Views, CR, CTR, CPC,
CPM.
4. Chọn ra những project có số Campaign_ads_name xuất hiện 3 lần và có Impressions lớn hơn150,000.
5. Chọn ra những project - lấy ra những chỉ số ở câu 3, có CR hơn KPIs - CR, có Impressions nhỏ hơn số Impressions trung
bình trên mỗi Keyword.
Buổi 3
Overview
Các nội dung chủ yếu:
- Hiểu được tầm quan trọng của CTE (Common Table Expression)
- Ghép bảng (Dùng LEFT, RIGHT, INNER JOIN VÀ UNION)
- Có thể hiểu được và vận dụng IF
- Có thể hiểu được và vận dụng CASE
- Xuất dữ liệu sang Google Data Studio
- Connect trực tiếp từ Google Data Studio đến Bigquery
CTE (Common Table
Expression)
CTE
Hiểu đơn giản, CTE là một nơi,
chúng ta lưu trữ dữ liệu được try
xuất một các tạm thời trong bộ
nhớ dưới một cái tên để có thể
dùng về sau.
- INNER JOIN
- LEFT JOIN
- RIGHT JOIN
- CROSS JOIN
- FULL JOIN
- SELF JOIN
GHÉP BẢNG
LEFT JOIN
KPIs_GoogleAds
Giống như phép toán giao tập hợp, INNER
JOIN ghép các dòng dữ liệu ở 2 bảng có 2
khóa giống nhau.
Syntax:
ON [Primary key]
GHÉP BẢNG
RIGHT JOIN
Tương tự như LEFT JOIN, RIGHT JOIN trả về tất The Result
cả giá trị của bảng số 2 và những giá trị có cùng
khoá chung ở bảng số 1. Nếu không có giá trị
phù hợp sẽ thể hiện NULL.
Kết quả trả về các cột của bảng GA_02 cộng The Result
với các cột của bảng KPIs_GoogleAds thông
qua khóa chính là Project
Syntax:
ON [Primary key]
GHÉP BẢNG
INNER JOIN
CASE
END
HÀM ĐIỀU KIỆN CASE
1. Tạo ra 2 CTE từ GA_02 và FB Ads, đặt tên là S1 và S2, Nhóm theo Date, Project - Sau đó Query S1, S2. Hint: FB chưa có
project, dùng CASE..WHEN..LIKE từ Campaign_ads_name để lấy ra Project (Các project là: Cassandra, Galinburg, LA Bee
One, Fox, Wolf, Funlus Phoenix, Royal Never Give Up).
2. Ghép bảng GA_02 vs KPIs_Google Ads (dùng LEFT JOIN, RIGHT JOIN, INNER JOIN). Hint: Tạo ra 2 CTE Nhóm theo Date,
Project, sau đó dùng LEFT JOIN,... (Primary keys: Date, Project)
3. Dùng UNION để kết hợp dữ liệu, Chọn ra: Date, Project, Channel, Cost, Impressions, Clicks, Conversion. Hint: Sử dụng kết
của của Câu 1.
4. Sử dụng CTE để nhóm bảng GA_02, Lấy ra Project, Cost (VND), Impressions, Clicks, Video Views, Conversions. Sau đó,
dùng LEFT JOIN với bảng KPIs_Google Ads để tạo 1 bảng mới gồm có Project, Cost (VND), Impressions, Clicks, Video
Views, Budget, KPIs Cost, KPIs Impressions, KPIs Clicks, KPIs Video Views.
Mini Project
Học viên sử dụng thêm các sheets: Age & Gender, Device, Day of week để phục vụ cho
thực hành.
Yêu cầu: Làm sạch dữ liệu từ GA_02, kết hợp với KPIs_Google Ads để phục vụ cho
visualization.
SELECT
first_name,
last_name,
grade,
DENSE_RANK() OVER (ORDER BY grade) grade_rank
FROM
students;
DATA FRAME
SELECT
s.first_name,
s.grade,
s.sport_id,
FIRST_VALUE (s.grade) OVER
(PARTITION BY s.sport_id
ORDER BY s.grade
) first_grade
FROM
students s;
DATA FRAME
SELECT
s.first_name,
s.sport_id,
s.grade,
LAG (s.grade) OVER (
ORDER BY s.grade
) lag_grade
FROM
students s;
CONVERT COLUMN1 TO COLUMN2
select
Identifier(id)
Identifier(sum) Select
( *
Identifier(sum) From
) Identifier(sale)
AS Where
Identifier(total_sale) Identifier(sale)
"SELECT * FROM b WHERE a > 0;" FROM INOp(IN)
Identifier(sum) (
select Identifier(orders) Select
* where Identifier(id)
from Identifier(id) FROM
Identifier(b) CompareOp(=) Identifier(users)
where IntLit(2) Where
Identifier(a) Group Identifier(status)
CompareOp(>) By CompareOp(=)
IntLit(0) Identifier(id) IntLit(0)
; )
select * from sale where user_id in (select id from users where status = 0)
"SELECT * FROM b WHERE a > 0;"
“SELECT * FROM b WHERE a > 0 ORDER BY a;”
SELECT sum(v)
FROM
(SELECT t1.id,
1 + 2 + t1.value AS v
FROM t1
JOIN t2
WHERE t1.id = t2.id
AND t2.id > 5000)
tmp
FULL OUTER JOIN
with UNION
Optimization Statement
Optimization Statement (cont)
Optimization Statement (cont)
Optimization Statement (cont)