Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
18 views

SQL Lesson 3_V2_1.1.0

Uploaded by

8jxbgbdcxs
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

SQL Lesson 3_V2_1.1.0

Uploaded by

8jxbgbdcxs
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 53

SQLITE ADVANCED FUNCTIONS

AND CONNECTION TO OTHER


APPLICATIONS
Today’s Objectives
--- One

• SQL AVG
• SQL COUNT
• SQL MAX
• SQL MIN
• SQL SUM
• SQLITE IMPORT .CSV
• SQLITE EXPORT .CSV
Today’s Objectives
--- Two

• SQLITE & PYTHON


INTRO
• CREATE DATABASE IN
PYTHON
• CREATE TABLE IN
PYTHON
• INSERT DATA IN
PYTHON
Today’s Objectives
--- Two

• UPDATE DATA IN
PYTHON
• DELETE DATA IN
PYTHON
• SELECT DATA IN
PYTHON
• REVIEW OF SQL
SESSION
SQLITE FUNCTIONS
FUNCTIONS – 函数
什么是函数 ?

在编程中,函数是一段代码的集合,是用来实现某一项特定的功能(通常是一项计算)的代码段
函数有输入变量和输出变量
SQLITE 中常用的函数:

AVG, MAX, MIN, COUNT, SUM


SQL AVG()
SQL 的 AVG 函数用于计算一组 non-null 的变量的均值。

AVG([ALL | DISTINCT] expression);

默认情况下,系统会自动使用 ALL 作为关键字,即所有非空变量都会被加入 AVG 的计算当中。如果我们只希


望计算不重复的变量,那么我们需要单独声明 DISTINCT 关键字。
SQL AVG()
AVG([ALL | DISTINCT] expression);

The AVG function is an aggregate function that calculates the average value
of all non-NULL values within a group.
CREATE TABLE avg_tests (val);

INSERT INTO avg_tests (val)


VALUES
(1),
(2),
(10.1),
(20.5),
('8'),
('B'),
(NULL),
(x'0010'),
(x'0011');
SQL AVG()
AVG([ALL | DISTINCT] expression);

The AVG function is an aggregate function that calculates the average value
of all non-NULL values within a group.

SELECT rowid,val
FROM avg_tests;

SELECT
avg(val)
FROM
avg_tests
WHERE
rowid < 5;

SELECT
avg(val)
FROM
avg_tests;
SQL AVG()
AVG([ALL | DISTINCT] expression);

The AVG function is an aggregate function that calculates the average value
of all non-NULL values within a group.

INSERT INTO avg_tests (val)


VALUES (10.1);

SELECT
avg(val)
FROM
avg_tests;

SELECT
avg(DISTINCT val)
FROM
avg_tests;
SQL AVG()
AVG([ALL | DISTINCT] expression);

The AVG function is an aggregate function that calculates the average value
of all non-NULL values within a group.
Another example:

SELECT
avg(milliseconds)
FROM
tracks;
SQL AVG()
AVG([ALL | DISTINCT] expression);

The AVG function is an aggregate function that calculates the average value
of all non-NULL values within a group.
SQLite AVG function with GROUP BY clause:

SELECT
albumid,
avg(milliseconds)
FROM
tracks
GROUP BY
albumid;
SQL AVG()
AVG([ALL | DISTINCT] expression);

The AVG function is an aggregate function that calculates the average value
of all non-NULL values within a group.
SQLite AVG function with INNER JOIN clause example:

SELECT
tracks.albumid,
title,
round(avg(milliseconds), 2) avg_length
FROM
tracks
INNER JOIN albums ON albums.AlbumId = tracks.albumid
GROUP BY
tracks.albumid;
SQL AVG()
AVG([ALL | DISTINCT] expression);

The AVG function is an aggregate function that calculates the average value
of all non-NULL values within a group.

SQLite AVG function with HAVING clause example:

SELECT
tracks.albumid,
title,
round(avg(milliseconds),2) avg_leng
FROM
tracks
INNER JOIN albums ON albums.AlbumId = tracks.albumid
GROUP BY
tracks.albumid
HAVING
avg_leng BETWEEN 100000 AND 200000;
SQL COUNT()
SQL 的 COUNT 函数用于返回一组非空变量的个数统计。

COUNT([ALL | DISTINCT] expression);

同样的,我们也可以选择 ALL 或者 DISTINCT 关键字,原理与 AVG 函数相同。

最简单的 COUNT 函数用法

COUNT(*) 用于返回一张表中所有行的计数。
SQL Count()
COUNT([ALL | DISTINCT] expression);

SQLite COUNT is an aggregate function that returns the number of items in


a group. For example, you can use the COUNT function to get the number of
tracks, the number of artists, playlists and the number of tracks in each
playlist, and so on.
SELECT
count(*)
FROM
tracks;

SELECT
count(*)
FROM
tracks
WHERE
albumid = 10;
SQL Count()
COUNT([ALL | DISTINCT] expression);

SQLite COUNT is an aggregate function that returns the number of items in


a group. For example, you can use the COUNT function to get the number of
tracks, the number of artists, playlists and the number of tracks in each
playlist, and so on.
SELECT SELECT
albumid, albumid,
count(*) count(*)
FROM FROM
tracks tracks
GROUP BY GROUP BY
albumid; albumid
HAVING count(*) > 25
SQL Count()
COUNT([ALL | DISTINCT] expression);

SQLite COUNT is an aggregate function that returns the number of items in


a group. For example, you can use the COUNT function to get the number of
tracks, the number of artists, playlists and the number of tracks in each
playlist, and so on.
SELECT
tracks.albumid,
name,
count(*)
FROM
tracks
INNER JOIN albums on albums.albumid = tracks.albumid
GROUP BY
tracks.albumid
HAVING count(*) > 25
ORDER BY COUNT(*) desc;
SQL Count()
COUNT([ALL | DISTINCT] expression);

SQLite COUNT is an aggregate function that returns the number of items in


a group. For example, you can use the COUNT function to get the number of
tracks, the number of artists, playlists and the number of tracks in each
playlist, and so on.
SQLite COUNT(DISTINCT expression) examples SELECT
SELECT COUNT(title)
employeeid, FROM
lastname, employees;
firstname,
title SELECT
FROM COUNT(DISTINCT title)
employees; FROM
employees;
SQLITE MAX
SQLITE 的 MAX 函数用于返回一个 group 中所有变量的最大值。灵活地使用 MAX 函数可以帮助我
们实现许多功能。如找到工资最高的 job title ,找到同一个 artist 名下销量最高的专辑等等。

• SQLITE 中 MAX 的基本语法如下:

MAX([ALL|DISTINCT] expression);
注意:
1. MAX 函数会自动忽略 NULL 值
2. DISTINCT 关键字不作用
3. 因为同一个 column 可以存储不同类型的 data ,包括 integer,real, text, blob 等,在使用
MAX 函数的时候,如果是可以识别的 text ,函数会转换成对应的数值,其他一律视为 0 。(参见
datatype 讲解)
SQL Max()
MAX([ALL|DISTINCT] expression);

The SQLite MAX function is an aggregate function that returns the


maximum value of all values in a group. You can use the MAX function to
accomplish a lot of things.

For example, you can use the MAX function to find the best item in terms of
price, rate, etc., or to find the highest item within its group.

-- biggest tracks
SELECT
MAX(bytes)
FROM
tracks;
SQL Max()
下面我们来看一下复杂的 query 语句中 MAX 函数的用法
SELECT
trackid,
name,
bytes
FROM
tracks
WHERE
bytes = (SELECT max(bytes) FROM tracks);

程序首先执行括号中的 select 语
句 , 将 tracks 表 中 最 大 的
bytes 选 出 来 , 然 后 以 此 作 为
constraint , 执 行 外 层 的
select 语句
SQL Max()
MAX 函数与 GROUP BY 相结合的用法
SELECT
albumid,
MAX(bytes)
FROM
tracks
GROUP BY
albumid;
SQL Max()
MAX 函数与 HAVING 相结合的用法
SELECT
albumid,
max(bytes)
FROM
tracks
GROUP BY
albumid
HAVING MAX(bytes) > 6000000;
SQLITE MIN
SQLITE 的 MIN 函数用于返回一个 group 中所有变量的最小值。其用法与注意事项与 MAX 类似。

• SQLITE 中 MIN 的基本语法如下:

MIN([ALL|DISTINCT] expression);
SQL Min()
MIN 函数的用法实例

SELECT
min(Milliseconds)
FROM
tracks;
SQL Min()
下面我们来看一下复杂的 query 语句中 MIN 函数的用法
SELECT
trackid,
name,
milliseconds
FROM
tracks
WHERE
milliseconds = (SELECT min(Milliseconds) FROM tracks);

程序首先执行括号中的 select 语句,将


tracks 表中最小的 milliseconds
选出来,然后以此作为 constraint ,
执行外层的 select 语句
SQL Min()
MIN 函数与 GROUP BY 结合的实例
SELECT
albumid,
min(milliseconds)
FROM
tracks
GROUP BY
albumid;
SQL Min()
MIN 函数与 HAVING 结合的实例
SELECT
albumid,
min(milliseconds)
FROM
tracks
GROUP BY
albumid
HAVING
MIN(milliseconds) < 10000;
SQLITE SUM
SQLITE 的 SUM 函数用于返回一个 group 中所有变量的和。

• SQLITE 中 SUM 的基本语法如下:

SUM([ALL|DISTINCT] expression);

函数 SUM 默认情况下会使用 ALL 关键字,即返回所有值得和。我们可以声明 DISTINCT 来计算不重


复变量的和。

注意:

1. 如果 sum 所作用的组中,有任意一个浮点数,那么结果就是浮点型

2. 只有所有变量值全为 NULL 时, sum 才会返回 NULL

3. 如果和值超过了允许的 integer 上限,会返回 exception


SQL SUM()
SUM 函数的实例
SELECT
SUM(milliseconds)
FROM
tracks;
SQL SUM()
SUM 函数与 GROUP BY 结合的实例
SELECT
albumid,
avg(milliseconds)
FROM
tracks
GROUP BY
albumid;
SQL SUM()
SUM 函数与 INNER JOIN 结合的实例
SELECT
tracks.albumid,
title,
SUM(milliseconds)
FROM
tracks
INNER JOIN albums ON albums.albumid = tracks.albumid
GROUP BY
tracks.albumid;
SQL SUM()
SUM 函数与 GROUP BY&HAVING 结合的实例
SELECT
tracks.albumid,
title,
SUM(milliseconds)
FROM
tracks
INNER JOIN albums ON albums.AlbumId = tracks.albumid
GROUP BY
tracks.albumid
HAVING
SUM(milliseconds) > 1000000;
SQLITE - PYTHON

1. 打开 Jupyter Notebook

2. 学会使用 pwd 命令查看工作目录

3. 学会使用 cd 命令到达想要的工作目录
SQLITE - PYTHON
import sqlite3
from sqlite3 import Error
引入 python 中自带的 sqlite3 模块
def create_connection():
""" create a database connection to a SQLite database """
try:
conn = sqlite3.connect('chinook.db')
print(sqlite3.version)
except Error as e:
print(e)
finally:
conn.close()
SQLITE - PYTHON
• 如果我们想要在 SQLITE 中直接添加表格,如,我们尝试建立以下两个表格 projects 和 tasks

CREATE TABLE IF NOT EXISTS projects (


id integer PRIMARY KEY,
name text NOT NULL,
begin_date text,
end_date text
);

-- tasks table
CREATE TABLE IF NOT EXISTS tasks (
id integer PRIMARY KEY,
name text NOT NULL,
priority integer,
project_id integer NOT NULL,
status_id integer NOT NULL,
begin_date text NOT NULL,
end_date text NOT NULL,
FOREIGN KEY (project_id) REFERENCES projects (id)
);
SQLITE - PYTHON
那么如何在 python 中来建立表格呢?如下

def create_table(conn, create_table_sql):


try:
c = conn.cursor()
c.execute(create_table_sql)
except Error as e:
print(e)
CREATE TABLE
那么如何在 python 中来建立表格呢?如下
def main(): # create a database connection
database = ”chinook.db" conn = create_connection(database)
if conn is not None:
sql_create_projects_table = """ CREATE TABLE IF NOT EXISTS projects ( # create projects table
id integer PRIMARY KEY, create_table(conn, sql_create_projects_table)
name text NOT NULL, # create tasks table
begin_date text, create_table(conn, sql_create_tasks_table)
end_date text else:
); """ print("Error! cannot create the database connection.")

sql_create_tasks_table = """CREATE TABLE IF NOT EXISTS tasks (


id integer PRIMARY KEY,
name text NOT NULL,
priority integer,
status_id integer NOT NULL,
project_id integer NOT NULL,
begin_date text NOT NULL,
end_date text NOT NULL,
FOREIGN KEY (project_id) REFERENCES projects (id)
);"""
CREATE TABLE
执行我们的 main 函数之后,就会成功创建两个表格了,与我们在 SQLITE STUDIO 中直接创建的表格
是一样的效果。

def main(): # create a database connection


database = ”chinook.db" conn = create_connection(database)
if conn is not None:
sql_create_projects_table = """ CREATE TABLE IF NOT EXISTS projects ( # create projects table
id integer PRIMARY KEY, create_table(conn, sql_create_projects_table)
name text NOT NULL, # create tasks table
begin_date text, create_table(conn, sql_create_tasks_table)
end_date text else:
); """ print("Error! cannot create the database connection.")

sql_create_tasks_table = """CREATE TABLE IF NOT EXISTS tasks (


id integer PRIMARY KEY,
name text NOT NULL,
priority integer,
status_id integer NOT NULL,
project_id integer NOT NULL,
begin_date text NOT NULL,
end_date text NOT NULL,
FOREIGN KEY (project_id) REFERENCES projects (id)
);"""
INSERT
创建一个向 projects 表格中添加 project 的函数,注意 VALUES 中的 ? 是占位符,会在程序调用的时
候被替换成我们输入的命令

def create_project(conn, project):


sql = ''' INSERT INTO projects(name,begin_date,end_date)
VALUES(?,?,?) '''
cur = conn.cursor()
cur.execute(sql, project)
return cur.lastrowid
INSERT
创建一个向 tasks 表格中添加 task 的函数

def create_task(conn, task):


sql = ''' INSERT INTO
tasks(name,priority,status_id,project_id,begin_date,end_date)
VALUES(?,?,?,?,?,?) '''
cur = conn.cursor()
cur.execute(sql, task)
return cur.lastrowid
INSERT
最后,我们写一个主函数来调用以上的添加数据函数

def main():
database = ”chinook.db"

# create a database connection


conn = create_connection(database)
with conn:
# create a new project
project = ('Cool App with SQLite & Python', '2015-01-01', '2015-01-30');
project_id = create_project(conn, project)

# tasks
task_1 = ('Analyze the requirements of the app', 1, 1, project_id, '2015-01-01', '2015-01-02')
task_2 = ('Confirm with user about the top requirements', 1, 1, project_id, '2015-01-03', '2015-01-05')

# create tasks
create_task(conn, task_1)
create_task(conn, task_2)
UPDATE
UPDATE 语句的调用,与 INSERT 非常类似

def update_task(conn, task):


sql = ''' UPDATE tasks
SET priority = ? ,
begin_date = ? ,
end_date = ?
WHERE id = ?'''
cur = conn.cursor()
cur.execute(sql, task)
UPDATE
然后我们还是写一个主函数来调用以上的 UPDATE 函数

def main():
database = " chinook.db"

# create a database connection


conn = create_connection(database)
with conn:
update_task(conn, (2, '2015-01-04', '2015-01-06',2))
UPDATE
我们仍然可以通过 studio 来验证刚才的 Python 代码是否生效,命令如下
SELECT
*
FROM
tasks
WHERE
id = 2;
DELETE
DELETE 语句的调用,首先我们来看如何删除特定的行

def delete_task(conn, id):


sql = 'DELETE FROM tasks WHERE id=?'
cur = conn.cursor()
cur.execute(sql, (id,))
DELETE
除了删除特定的行之外,我们还可以删除整个表中所有行的内容。只需要去掉原语句中的 WHERE 限制就可以了。

def delete_all_tasks(conn):
sql = 'DELETE FROM tasks'
cur = conn.cursor()
cur.execute(sql)
DELETE
下面我们来写主函数

def main():
database = ”chinook.db"

# create a database connection


conn = create_connection(database)
with conn:
delete_task(conn, 2);
#delete_all_tasks(conn);
SELECT
最后我们来学习一下 SELECT 语句在 Python 中的调用,首先我们写一个函数,用来调出所有 tasks 表中
的行并打印出来

def select_all_tasks(conn):
cur = conn.cursor()
cur.execute("SELECT * FROM tasks")

rows = cur.fetchall()

for row in rows:


print(row)
SELECT
我们还可以添加 WHERE 语句来添加限制,打印特定的行

def select_task_by_priority(conn, priority):


cur = conn.cursor()
cur.execute("SELECT * FROM tasks WHERE priority=?", (priority,))

rows = cur.fetchall()

for row in rows:


print(row)
SELECT
同样地,我们需要写出一个主函数来调用上面的两个函数

def main():
database = ”chinook.db"

# create a database connection


conn = create_connection(database)
with conn:
print("1. Query task by priority:")
select_task_by_priority(conn,1)

print("2. Query all tasks")


select_all_tasks(conn)
回顾与复习
在最后一节 SQL 课的末尾,我们来回顾一下三节课的 SQL 内容。以下是我们整个课程涵盖的内容:

SQLite Select SQLite Left Join SQLite AVG


SQLite Order By SQLite Inner Join SQLite COUNT
SQLite Select Distinct SQLite Cross Join SQLite MAX
SQLite Where SQLite Self-Join SQLite MIN
SQLite Limit SQLite Data Types SQLite SUM

SQLite GLOB SQLite Primary Key SQLite Import CSV

SQLite Union SQLite Foreign Key SQLite Export CSV


SQLite Full Outer Join SQLite AUTOINCREMENT SQLite Python - Create Connection
SQLite Having SQLite Alter Table SQLite Python - Create database
SQLite Case SQLite Drop Table SQLite Python - Create Table
SQLite Insert SQLite Create View SQLite Python - Insert Data
SQLite Update SQLite Index SQLite Python - Update Data
SQLite Delete SQLite Index SQLite Python - Delete Data
SQLite Replace SQLite Full-text Search SQLite Python - Select
谢谢!

You might also like