蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行 SQLite 3.53 GROUP BY 单表求和、多表 LEFT JOIN 分组计数与零日志站点对比实测

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-groupby.py
explore-groupby.py166 行
"""SQL GROUP BY 离线实验:验证单列分组求和、多表 LEFT JOIN 分组计数、多列分组及无日志站点差异。"""
import json
import platform
import sqlite3


def seed_tables(conn: sqlite3.Connection) -> None:
    conn.executescript(
        """
        CREATE TABLE websites (
            id INTEGER PRIMARY KEY,
            name TEXT NOT NULL,
            url TEXT NOT NULL,
            alexa INTEGER NOT NULL,
            country TEXT NOT NULL
        );
        INSERT INTO websites (id, name, url, alexa, country) VALUES
            (1, 'Google', 'https://www.google.com/', 1, 'USA'),
            (2, '淘宝', 'https://www.taobao.com/', 13, 'CN'),
            (3, '蓝色天空', 'http://www.mbsky.com/', 4689, 'CN'),
            (4, '微博', 'http://weibo.com/', 20, 'CN'),
            (5, 'Facebook', 'https://www.facebook.com/', 3, 'USA'),
            (7, 'stackoverflow', 'http://stackoverflow.com/', 0, 'IND');

        CREATE TABLE access_log (
            aid INTEGER PRIMARY KEY,
            site_id INTEGER NOT NULL,
            count INTEGER NOT NULL,
            date TEXT NOT NULL
        );
        INSERT INTO access_log (aid, site_id, count, date) VALUES
            (1, 1, 45, '2016-05-10'),
            (2, 3, 100, '2016-05-13'),
            (3, 1, 230, '2016-05-14'),
            (4, 2, 10, '2016-05-14'),
            (5, 5, 205, '2016-05-14'),
            (6, 4, 13, '2016-05-15'),
            (7, 3, 220, '2016-05-15'),
            (8, 5, 545, '2016-05-16'),
            (9, 3, 201, '2016-05-17');
        """
    )


def run() -> dict:
    conn = sqlite3.connect(":memory:")
    seed_tables(conn)
    cases = []

    # Case 1: Single-table GROUP BY site_id with SUM(count)
    rows1 = [
        list(r)
        for r in conn.execute(
            """
            SELECT site_id, SUM(access_log.count) AS nums
            FROM access_log
            GROUP BY site_id
            ORDER BY site_id;
            """
        ).fetchall()
    ]
    exp1 = [[1, 275], [2, 10], [3, 521], [4, 13], [5, 750]]
    cases.append(
        {
            "name": "groupby_site_id_sum_count",
            "summary": "对 access_log 按 site_id 分组统计各站点访问量总和",
            "expected": exp1,
            "actual": rows1,
            "passed": rows1 == exp1,
        }
    )

    # Case 2: Multi-table LEFT JOIN (access_log LEFT JOIN websites) + GROUP BY websites.name
    rows2 = [
        list(r)
        for r in conn.execute(
            """
            SELECT websites.name, COUNT(access_log.aid) AS nums
            FROM access_log
            LEFT JOIN websites ON access_log.site_id = websites.id
            GROUP BY websites.name
            ORDER BY nums DESC, websites.name ASC;
            """
        ).fetchall()
    ]
    exp2 = [
        ["蓝色天空", 3],
        ["Facebook", 2],
        ["Google", 2],
        ["微博", 1],
        ["淘宝", 1],
    ]
    cases.append(
        {
            "name": "groupby_multitable_join_count",
            "summary": "以 access_log LEFT JOIN websites 按站点名分组统计有日志站点的记录条数",
            "expected": exp2,
            "actual": rows2,
            "passed": rows2 == exp2,
        }
    )

    # Case 3: Reversing LEFT JOIN direction to retain zero-log sites + multi-column GROUP BY with WHERE
    zero_included = [
        list(r)
        for r in conn.execute(
            """
            SELECT websites.name, COUNT(access_log.aid) AS log_rows, COALESCE(SUM(access_log.count), 0) AS total_views
            FROM websites
            LEFT JOIN access_log ON websites.id = access_log.site_id
            GROUP BY websites.id, websites.name
            ORDER BY websites.id;
            """
        ).fetchall()
    ]
    by_country_date = [
        list(r)
        for r in conn.execute(
            """
            SELECT websites.country, access_log.date, SUM(access_log.count) AS daily_views
            FROM websites
            INNER JOIN access_log ON websites.id = access_log.site_id
            WHERE access_log.date = '2016-05-14'
            GROUP BY websites.country, access_log.date
            ORDER BY websites.country;
            """
        ).fetchall()
    ]
    exp3 = {
        "websites_left_join_all": [
            ["Google", 2, 275],
            ["淘宝", 1, 10],
            ["蓝色天空", 3, 521],
            ["微博", 1, 13],
            ["Facebook", 2, 750],
            ["stackoverflow", 0, 0],
        ],
        "country_date_2016_05_14": [
            ["CN", "2016-05-14", 10],
            ["USA", "2016-05-14", 435],
        ],
    }
    act3 = {
        "websites_left_join_all": zero_included,
        "country_date_2016_05_14": by_country_date,
    }
    cases.append(
        {
            "name": "groupby_zero_match_and_multicolumn",
            "summary": "对比 websites LEFT JOIN 保留零记录站点 stackoverflow 及 WHERE 后多列分组聚合",
            "expected": exp3,
            "actual": act3,
            "passed": act3 == exp3,
        }
    )

    conn.close()
    return {
        "version": f"CPython {platform.python_version()} / SQLite {sqlite3.sqlite_version}",
        "cases": cases,
    }


if __name__ == "__main__":
    print(json.dumps(run(), ensure_ascii=False, indent=2))
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/sql-groupby-lab/explore-groupby.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-groupby.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:SQL

课程关联工程包(登记关联67章) · 含当前章节或实例 · mbskycom202612a1523.zip

下载课程关联工程包:SQL

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1555.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习