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

运行 SQLite 3.53 WHERE 聚合报错验证、HAVING 分组过滤及 WHERE+HAVING 联用实测

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-having.py
explore-having.py140 行
"""SQL HAVING 离线实验:验证 WHERE 禁止聚合报错、HAVING 筛选分组总访问量及 WHERE 与 HAVING 联用顺序。"""
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: WHERE cannot use aggregate functions -> OperationalError
    where_agg_error = None
    try:
        conn.execute(
            "SELECT site_id, SUM(count) FROM access_log WHERE SUM(count) > 200 GROUP BY site_id;"
        )
    except sqlite3.OperationalError as exc:
        where_agg_error = str(exc)
    exp1 = {"rejected_in_where": True, "mentions_misuse": True}
    act1 = {
        "rejected_in_where": where_agg_error is not None,
        "mentions_misuse": bool(where_agg_error and "misuse of aggregate" in where_agg_error.lower()),
    }
    cases.append(
        {
            "name": "where_rejects_aggregate_function",
            "summary": "验证在 WHERE 子句中直接使用 SUM(count) 会触发数据库聚合误用错误",
            "expected": exp1,
            "actual": act1,
            "passed": act1 == exp1,
        }
    )

    # Case 2: HAVING SUM(access_log.count) > 200
    rows2 = [
        list(r)
        for r in conn.execute(
            """
            SELECT websites.name, websites.url, SUM(access_log.count) AS nums
            FROM access_log
            INNER JOIN websites ON access_log.site_id = websites.id
            GROUP BY websites.name, websites.url
            HAVING SUM(access_log.count) > 200
            ORDER BY nums DESC;
            """
        ).fetchall()
    ]
    exp2 = [
        ["Facebook", "https://www.facebook.com/", 750],
        ["蓝色天空", "http://www.mbsky.com/", 521],
        ["Google", "https://www.google.com/", 275],
    ]
    cases.append(
        {
            "name": "having_total_views_gt_200",
            "summary": "使用 GROUP BY + HAVING SUM(access_log.count) > 200 筛选总访问量超过 200 的站点",
            "expected": exp2,
            "actual": rows2,
            "passed": rows2 == exp2,
        }
    )

    # Case 3: Combining WHERE (row-level filter before grouping) + HAVING (group-level filter after grouping)
    rows3 = [
        list(r)
        for r in conn.execute(
            """
            SELECT websites.name, SUM(access_log.count) AS nums
            FROM websites
            INNER JOIN access_log ON websites.id = access_log.site_id
            WHERE websites.alexa < 200
            GROUP BY websites.name
            HAVING SUM(access_log.count) > 200
            ORDER BY nums DESC;
            """
        ).fetchall()
    ]
    exp3 = [
        ["Facebook", 750],
        ["Google", 275],
    ]
    cases.append(
        {
            "name": "where_before_groupby_then_having",
            "summary": "先用 WHERE websites.alexa < 200 排除排名 >= 200 的行,再用 HAVING SUM > 200 筛选分组",
            "expected": exp3,
            "actual": rows3,
            "passed": rows3 == 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-having-lab/explore-having.py

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

下载课程关联工程包:SQL

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

下载课程关联工程包:SQL

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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