工程与学习方法 / 12.1

SQL练习:连接、收入与分组排名

工具、语法与实践中的边界。 SQL练习:连接、收入与分组排名。

阅读说明: 保留原笔记的编号与章节顺序;代码只供查看,没有在本站运行。历史输出不代表当前版本的复现结果。截图/外链图以独立整理的公式、表格、示意或文字替换;纠错与必要补充均作说明。

1. Enviroment Setup

1.1 SQL Setup

PYTHON · 仅供阅读
# After Restart runtime, run this cell
import sqlite3 as lite
import pandas as pd

1.2 Create SQL 2 and 3 tables and import data

PYTHON · 仅供阅读
#@title Run this cell to create tables and import data
conn = lite.connect('test.db',timeout=10)
cur= conn.cursor()

# create SQL 2 tables and data
cur.execute("Drop TABLE IF EXISTS customers")
cur.execute("CREATE TABLE IF NOT EXISTS customers(customerid INTEGER, country TEXT)")

cur.execute("Drop TABLE IF EXISTS categories")
cur.execute("CREATE TABLE IF NOT EXISTS categories(categoryid INTEGER, categoryname TEXT)")

cur.execute("Drop TABLE IF EXISTS employees")
cur.execute("CREATE TABLE IF NOT EXISTS employees(employeeid INTEGER, birthdate BLOB)")

cur.execute("Drop TABLE IF EXISTS orderdetails")
cur.execute("CREATE TABLE IF NOT EXISTS orderdetails(orderid INTEGER, productid INTEGER, quantity INTEGER)")

cur.execute("Drop TABLE IF EXISTS orders")
cur.execute("CREATE TABLE IF NOT EXISTS orders(orderid INTEGER, customerid INTEGER)")

cur.execute("Drop TABLE IF EXISTS products")
cur.execute("CREATE TABLE IF NOT EXISTS products(productid INTEGER, categoryid INTEGER, price INTEGER)")


insert_query_customers='''
INSERT INTO customers
    ("customerid", "country")
VALUES
    (1, 'Germany'),
    (2, 'Mexico'),
    (3, 'Mexico'),
    (4, 'UK'),
    (5, 'Sweden'),
    (6, 'Germany'),
    (7, 'France'),
    (8, 'Spain'),
    (9, 'France'),
    (10, 'Canada'),
    (11, 'UK'),
    (12, 'Argentina'),
    (13, 'Mexico'),
    (14, 'Switzerland'),
    (15, 'Brazil'),
    (16, 'UK'),
    (17, 'Germany'),
    (18, 'France'),
    (19, 'UK'),
    (20, 'Austria')
;
'''

insert_query_categories='''
INSERT INTO categories
    ("categoryid", "categoryname")
VALUES
    (1, 'Beverages'),
    (2, 'Condiments'),
    (3, 'Confections'),
    (4, 'Dairy Products'),
    (5, 'Grains/Cereals'),
    (6, 'Meat/Poultry'),
    (7, 'Produce'),
    (8, 'Seafood')
;
'''

insert_query_employees='''
INSERT INTO employees
    ("employeeid", "birthdate")
VALUES
    (1, '1968-12-08'),
    (2, '1952-02-19'),
    (3, '1963-08-30'),
    (4, '1958-09-19'),
    (5, '1955-03-04')
;
'''
insert_query_orderdetails='''
INSERT INTO orderdetails
    ("orderid", "productid", "quantity")
VALUES
    (10248, 11, 12),
    (10248, 42, 10),
    (10248, 72, 5),
    (10249, 14, 9),
    (10249, 51, 40),
    (10250, 41, 10),
    (10250, 51, 35),
    (10250, 65, 15),
    (10251, 22, 6),
    (10251, 57, 15),
    (10251, 65, 20),
    (10252, 20, 40),
    (10252, 33, 25),
    (10252, 60, 40),
    (10253, 31, 20),
    (10253, 39, 42),
    (10253, 49, 40),
    (10254, 24, 15),
    (10254, 55, 21),
    (10254, 74, 21),
    (10255, 2, 20),
    (10255, 16, 35),
    (10255, 36, 25),
    (10255, 59, 30),
    (10256, 53, 15),
    (10256, 77, 12),
    (10257, 27, 25),
    (10257, 39, 6),
    (10257, 77, 15),
    (10258, 2, 50),
    (10258, 5, 65),
    (10258, 32, 6),
    (10259, 21, 10),
    (10259, 37, 1),
    (10260, 41, 16),
    (10260, 57, 50),
    (10260, 62, 15),
    (10260, 70, 21),
    (10261, 21, 20),
    (10261, 35, 20),
    (10262, 5, 12),
    (10262, 7, 15),
    (10262, 56, 2),
    (10263, 16, 60),
    (10263, 24, 28),
    (10263, 30, 60),
    (10263, 74, 36),
    (10264, 2, 35),
    (10264, 41, 25),
    (10265, 17, 30),
    (10265, 70, 20),
    (10266, 12, 12),
    (10267, 40, 50),
    (10267, 59, 70),
    (10267, 76, 15),
    (10268, 29, 10),
    (10268, 72, 4),
    (10269, 33, 60),
    (10269, 72, 20),
    (10270, 36, 30),
    (10270, 43, 25),
    (10271, 33, 24),
    (10272, 20, 6),
    (10272, 31, 40),
    (10272, 72, 24),
    (10273, 10, 24),
    (10273, 31, 15),
    (10273, 33, 20),
    (10273, 40, 60),
    (10273, 76, 33),
    (10274, 71, 20),
    (10274, 72, 7),
    (10275, 24, 12),
    (10275, 59, 6),
    (10276, 10, 15),
    (10276, 13, 10),
    (10277, 28, 20),
    (10277, 62, 12),
    (10278, 44, 16),
    (10278, 59, 15),
    (10278, 63, 8),
    (10278, 73, 25),
    (10279, 17, 15),
    (10280, 24, 12),
    (10280, 55, 20),
    (10280, 75, 30),
    (10281, 19, 1),
    (10281, 24, 6),
    (10281, 35, 4),
    (10282, 30, 6),
    (10282, 57, 2),
    (10283, 15, 20),
    (10283, 19, 18),
    (10283, 60, 35),
    (10283, 72, 3),
    (10284, 27, 15),
    (10284, 44, 21),
    (10284, 60, 20),
    (10284, 67, 5)
;
'''

insert_query_orders='''
INSERT INTO orders
    ("orderid", "customerid")
VALUES
    (10248, 90),
    (10249, 81),
    (10250, 34),
    (10251, 84),
    (10252, 76),
    (10253, 34),
    (10254, 14),
    (10255, 68),
    (10256, 88),
    (10257, 35),
    (10258, 20),
    (10259, 13),
    (10260, 55),
    (10261, 61),
    (10262, 65),
    (10263, 20),
    (10264, 24),
    (10265, 7),
    (10266, 87)
;
'''

insert_query_products='''
INSERT INTO products
    ("productid", "categoryid", "price")
VALUES
    (1, 1, 18),
    (2, 1, 19),
    (3, 2, 10),
    (4, 2, 22),
    (5, 2, 21.35),
    (6, 2, 25),
    (7, 7, 30),
    (8, 2, 40),
    (9, 6, 97),
    (10, 8, 31),
    (11, 4, 21),
    (12, 4, 38),
    (13, 8, 6),
    (14, 7, 23.25),
    (15, 2, 15.5),
    (16, 3, 17.45),
    (17, 6, 39),
    (18, 8, 62.5),
    (19, 3, 9.2),
    (20, 3, 81),
    (21, 3, 10),
    (22, 5, 21),
    (23, 5, 9),
    (24, 1, 4.5),
    (25, 3, 14),
    (26, 3, 31.23),
    (27, 3, 43.9),
    (28, 7, 45.6),
    (29, 6, 123.79),
    (30, 8, 25.89),
    (31, 4, 12.5),
    (32, 4, 32),
    (33, 4, 2.5),
    (34, 1, 14),
    (35, 1, 18),
    (36, 8, 19),
    (37, 8, 26),
    (38, 1, 263.5),
    (39, 1, 18),
    (40, 8, 18.4),
    (41, 8, 9.65),
    (42, 5, 14),
    (43, 1, 46),
    (44, 2, 19.45),
    (45, 8, 9.5),
    (46, 8, 12),
    (47, 3, 9.5),
    (48, 3, 12.75),
    (49, 3, 20)
;
'''


cur.execute(insert_query_customers)
cur.execute(insert_query_categories)
cur.execute(insert_query_employees)
cur.execute(insert_query_orderdetails)
cur.execute(insert_query_orders)
cur.execute(insert_query_products)

# create SQL 3 tables and data
cur.execute("Drop TABLE IF EXISTS highschooler")
cur.execute("CREATE TABLE IF NOT EXISTS highschooler(id INTEGER, name TEXT, grade INTEGER)")

cur.execute("Drop TABLE IF EXISTS friend")
cur.execute("CREATE TABLE IF NOT EXISTS friend(id1 INTEGER, id2 INTEGER)")

cur.execute("Drop TABLE IF EXISTS likes")
cur.execute("CREATE TABLE IF NOT EXISTS likes(id1 INTEGER, id2 INTEGER)")

cur.execute("Drop TABLE IF EXISTS movie")
cur.execute("CREATE TABLE IF NOT EXISTS movie(mid INTEGER, title TEXT, year INTEGER, director TEXT)")

cur.execute("Drop TABLE IF EXISTS reviewer")
cur.execute("CREATE TABLE IF NOT EXISTS reviewer(rid INTERGER, name TEXT)")

cur.execute("Drop TABLE IF EXISTS rating")
cur.execute("CREATE TABLE IF NOT EXISTS rating(rid INTERGER, mid INTERGER, stars INTERGER, ratingdate BLOB)")

insert_query_highschooler='''
insert into highschooler("id","name","grade") 
values 
(1510, 'Jordan', 9),
(1689, 'Gabriel', 9),
(1381, 'Tiffany', 9),
(1709, 'Cassandra', 9),
(1101, 'Haley', 10),
(1782, 'Andrew', 10),
(1468, 'Kris', 10),
(1641, 'Brittany', 10),
(1247, 'Alexis', 11),
(1316, 'Austin', 11),
(1911, 'Gabriel', 11),
(1501, 'Jessica', 11),
(1304, 'Jordan', 12),
(1025, 'John', 12),
(1934, 'Kyle', 12),
(1661, 'Logan', 12);
'''
insert_query_friend='''
insert into friend("id1","id2") 
values 
(1510, 1381),
(1101, 1501),
(1510, 1689),
(1689, 1709),
(1381, 1247),
(1709, 1247),
(1689, 1782),
(1782, 1468),
(1782, 1316),
(1782, 1304),
(1468, 1101),
(1468, 1641),
(1101, 1641),
(1247, 1911),
(1247, 1501),
(1911, 1501),
(1501, 1934),
(1316, 1934),
(1934, 1304),
(1304, 1661),
(1661, 1025),
(1689, 1709),
(1709, 1689),
(1782, 1709),
(1911, 1247),
(1247, 1468),
(1641, 1468),
(1316, 1304),
(1501, 1934),
(1934, 1501),
(1025, 1101);
'''
insert_query_likes='''
insert into likes("id1","id2")
values 
(1689, 1709),
(1709, 1689),
(1782, 1709),
(1911, 1247),
(1247, 1468),
(1641, 1468),
(1316, 1304),
(1501, 1934),
(1934, 1501),
(1025, 1101),
(1101, 1381),
(1025, 1641);

'''
insert_query_movie='''
insert into movie("mid","title","year","director") 
values
(101, 'Gone with the Wind', 1939, 'Victor Fleming'),
(102, 'Star Wars', 1977, 'George Lucas'),
(103, 'The Sound of Music', 1965, 'Robert Wise'),
(104, 'E.T.', 1982, 'Steven Spielberg'),
(105, 'Titanic', 1997, 'James Cameron'),
(106, 'Snow White', 1937, null),
(107, 'Avatar', 2009, 'James Cameron'),
(108, 'Raiders of the Lost Ark', 1981, 'Steven Spielberg');

'''
insert_query_reviewer='''
insert into reviewer("rid","name") 
values
(201, 'Sarah Martinez'),
(202, 'Daniel Lewis'),
(203, 'Brittany Harris'),
(204, 'Mike Anderson'),
(205, 'Chris Jackson'),
(206, 'Elizabeth Thomas'),
(207, 'James Cameron'),
(208, 'Ashley White');

'''
insert_query_rating='''
insert into rating("rid", "mid", "stars", "ratingdate")
values
(201, 101, 2, '2011-01-22'),
(201, 101, 4, '2011-01-27'),
(202, 106, 4, null),
(203, 103, 2, '2011-01-20'),
(203, 108, 4, '2011-01-12'),
(203, 108, 2, '2011-01-30'),
(204, 101, 3, '2011-01-09'),
(205, 103, 3, '2011-01-27'),
(205, 104, 2, '2011-01-22'),
(205, 108, 4, null),
(206, 107, 3, '2011-01-15'),
(206, 106, 5, '2011-01-19'),
(207, 107, 5, '2011-01-20'),
(208, 104, 3, '2011-01-02');
'''
cur.execute(insert_query_highschooler)
cur.execute(insert_query_friend)
cur.execute(insert_query_likes)
cur.execute(insert_query_movie)
cur.execute(insert_query_reviewer)
cur.execute(insert_query_rating)


conn.commit()

1.3 Practice your query

PYTHON · 仅供阅读
# write your queries inside query as a string variable
query = '''
with cte as
(
      select id1 as id
      from friend
      where id2 in (
		select id
		from highschooler
		where name='Gabriel'
		)
      union
      select id2 as id
      from friend
      where id1 in (
	           select id
		from highschooler
	where name='Gabriel'
		)
)
Select a.*
from highschooler a join cte on a.id=cte.id;

'''

# run script
pd.read_sql_query(query,conn)
原笔记输出 · 本次未执行
     id       name  grade
0  1510     Jordan      9
1  1709  Cassandra      9
2  1782     Andrew     10
3  1247     Alexis     11
4  1501    Jessica     11

2. Exercise

表关系: customers(customerid) → orders(customerid,orderid) → orderdetails(orderid,productid,quantity) ← products(productid,categoryid,price) ← categories(categoryid,categoryname)。按国家汇总数量、收入时,应注意一对多连接会展开行,订单数需COUNT DISTINCT。

2.1 Total sales(quantity) by country

PYTHON · 仅供阅读
# FROM customers AS a中AS可省略
query = '''
SELECT a.country,
       SUM(CASE WHEN c.quantity IS NOT null THEN c.quantity else 0 END) as total_sales 
FROM customers a
LEFT JOIN orders b ON a.customerid=b.customerid
LEFT JOIN orderdetails c ON b.orderid=c.orderid
GROUP BY a.country
ORDER BY a.country;
'''

# run script
pd.read_sql_query(query, conn)
原笔记输出 · 本次未执行
        country  total_sales
0     Argentina            0
1       Austria          305
2        Brazil            0
3        Canada            0
4        France           50
5       Germany            0
6        Mexico           11
7         Spain            0
8        Sweden            0
9   Switzerland           57
10           UK            0

2.2 Revenue by country

PYTHON · 仅供阅读
query = '''
SELECT a.country,
       SUM(c.quantity*d.price) as revenue 
FROM customers a
LEFT JOIN orders b ON a.customerid=b.customerid
LEFT JOIN orderdetails c ON b.orderid=c.orderid
LEFT JOIN products d ON c.productid=d.productid
GROUP BY a.country
ORDER BY a.country;
'''

# run script
pd.read_sql_query(query, conn)
原笔记输出 · 本次未执行
        country  revenue
0     Argentina      NaN
1       Austria  5256.15
2        Brazil      NaN
3        Canada      NaN
4        France  1170.00
5       Germany      NaN
6        Mexico   126.00
7         Spain      NaN
8        Sweden      NaN
9   Switzerland    67.50
10           UK      NaN

2.3 Revenue by category in Austria

PYTHON · 仅供阅读
query = '''
SELECT a.country,
       d.categoryid, 
       SUM(c.quantity*d.price) AS revenue 
FROM customers a
JOIN orders b ON a.customerid=b.customerid
JOIN orderdetails c ON b.orderid=c.orderid
JOIN products d ON c.productid=d.productid
WHERE a.country = 'Austria'
GROUP BY 1,2
ORDER BY 1,2;
'''

# run script
pd.read_sql_query(query, conn)
原笔记输出 · 本次未执行
   country  categoryid  revenue
0  Austria           1  1076.00
1  Austria           2  1387.75
2  Austria           3  1047.00
3  Austria           4   192.00
4  Austria           8  1553.40

2.4 For each customer, what’s their average spend(total spend/total order)?

PYTHON · 仅供阅读
query = '''
SELECT a.customerid,
       COUNT(DISTINCT c.orderid) AS orders,       
       SUM(c.quantity*d.price) AS spend,
       SUM(c.quantity*d.price)/COUNT(DISTINCT c.orderid) AS avg_spend
FROM customers a
JOIN orders b ON a.customerid=b.customerid
JOIN orderdetails c ON b.orderid=c.orderid
JOIN products d ON c.productid=d.productid
GROUP BY 1
ORDER BY 1;
'''

# run script
pd.read_sql_query(query, conn)
原笔记输出 · 本次未执行
   customerid  orders    spend  avg_spend
0           7       1  1170.00   1170.000
1          13       1   126.00    126.000
2          14       1    67.50     67.500
3          20       2  5256.15   2628.075
PYTHON · 仅供阅读
query = '''
SELECT *
FROM (
    SELECT categoryid,
           productid,
           sales,
           ROW_NUMBER() OVER(PARTITION BY categoryid ORDER BY sales DESC) AS row_num
    FROM (
        SELECT a.categoryid,
               a.productid,
               SUM(b.quantity) AS sales
        FROM products a
        JOIN orderdetails b
        ON a.productid=b.productid
        GROUP BY 1,2
    ) AS foo
) AS foo_1
WHERE row_num<=5;
'''

# run script
pd.read_sql_query(query, conn)
原笔记输出 · 本次未执行
    categoryid  productid  sales  row_num
0            1          2    105        1
1            1         24     73        2
2            1         39     48        3
3            1         43     25        4
4            1         35     24        5
5            2          5     77        1
6            2         44     37        2
7            2         15     20        3
8            3         16     95        1
9            3         20     46        2
10           3         27     40        3
11           3         49     40        4
12           3         21     30        5
13           4         33    129        1
14           4         31     75        2
15           4         11     12        3
16           4         12     12        4
17           4         32      6        5
18           5         42     10        1
19           5         22      6        2
20           6         17     45        1
21           6         29     10        2
22           7         28     20        1
23           7          7     15        2
24           7         14      9        3
25           8         40    110        1
26           8         30     66        2
27           8         36     55        3
28           8         41     51        4
29           8         10     39        5

2.6 Reporting: Each customer quantity on beverage, condiments, and others

PYTHON · 仅供阅读
query = '''
SELECT a.customerid,
       SUM(CASE WHEN e.categoryname='Beverages' THEN c.quantity ELSE 0 END) AS bev_sales,
       SUM(CASE WHEN e.categoryname='Condiments' THEN c.quantity ELSE 0 END) AS condi_sales,
       SUM(CASE WHEN e.categoryname NOT IN ('Beverages', 'Condiments') 
           THEN c.quantity ELSE 0 END) AS other_sales
FROM customers a
LEFT JOIN orders b ON a.customerid=b.customerid
LEFT JOIN orderdetails c ON b.orderid=c.orderid
LEFT JOIN products d ON c.productid=d.productid
LEFT JOIN categories e ON d.categoryid=e.categoryid
GROUP BY 1
ORDER BY 1;
'''

# run script
pd.read_sql_query(query, conn)
原笔记输出 · 本次未执行
    customerid  bev_sales  condi_sales  other_sales
0            1          0            0            0
1            2          0            0            0
2            3          0            0            0
3            4          0            0            0
4            5          0            0            0
5            6          0            0            0
6            7          0            0           30
7            8          0            0            0
8            9          0            0            0
9           10          0            0            0
10          11          0            0            0
11          12          0            0            0
12          13          0            0           11
13          14         15            0           15
14          15          0            0            0
15          16          0            0            0
16          17          0            0            0
17          18          0            0            0
18          19          0            0            0
19          20         78           65          269

版本说明: 上方代码含局部修正;下方/相邻输出来自原笔记运行记录(隐私字段已占位),不是本次重新运行修正版得到的结果。

整理参考资料