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

运行 SQLite 3.53 单列去重、多列元组去重及 NULL/COUNT(DISTINCT) 实测

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-distinct.py
explore-distinct.py135 行
"""SQL SELECT DISTINCT 离线实验:验证单列去重、多列组合去重以及 NULL 与 COUNT(DISTINCT) 行为。"""
import json
import platform
import sqlite3


def run() -> dict:
    conn = sqlite3.connect(":memory:")
    conn.executescript(
        """
        CREATE TABLE websites (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT NOT NULL,
            url TEXT NOT NULL,
            alexa INTEGER NOT NULL,
            country TEXT
        );
        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');
        """
    )
    cases = []

    # Case 1: Single-column DISTINCT vs non-DISTINCT
    raw_countries = [
        r[0] for r in conn.execute("SELECT country FROM websites ORDER BY id;").fetchall()
    ]
    distinct_countries = [
        r[0]
        for r in conn.execute(
            "SELECT DISTINCT country FROM websites ORDER BY country ASC;"
        ).fetchall()
    ]
    exp1 = {
        "raw_count": 5,
        "distinct_count": 2,
        "distinct_values": ["CN", "USA"],
    }
    act1 = {
        "raw_count": len(raw_countries),
        "distinct_count": len(distinct_countries),
        "distinct_values": distinct_countries,
    }
    cases.append(
        {
            "name": "select_distinct_single_column",
            "summary": "对比 SELECT country 与 SELECT DISTINCT country,验证 5 行去重为 CN 与 USA 2 个唯一值",
            "expected": exp1,
            "actual": act1,
            "passed": act1 == exp1,
        }
    )

    # Case 2: Multi-column DISTINCT operates on tuple combinations
    conn.executescript(
        """
        CREATE TABLE channels (
            id INTEGER PRIMARY KEY,
            country TEXT,
            tier TEXT
        );
        INSERT INTO channels VALUES
            (1, 'CN', 'A'),
            (2, 'CN', 'A'),
            (3, 'CN', 'B'),
            (4, 'USA', 'A'),
            (5, 'USA', 'A');
        """
    )
    combos = [
        list(r)
        for r in conn.execute(
            "SELECT DISTINCT country, tier FROM channels ORDER BY country, tier;"
        ).fetchall()
    ]
    exp2 = [["CN", "A"], ["CN", "B"], ["USA", "A"]]
    act2 = combos
    cases.append(
        {
            "name": "select_distinct_multi_column",
            "summary": "验证多列 SELECT DISTINCT 作用于整组列值组合而非仅首列",
            "expected": exp2,
            "actual": act2,
            "passed": act2 == exp2,
        }
    )

    # Case 3: DISTINCT with multiple NULLs and COUNT(DISTINCT col)
    conn.execute(
        "INSERT INTO websites (name, url, alexa, country) VALUES ('DraftA', 'https://a.example/', 100, NULL);"
    )
    conn.execute(
        "INSERT INTO websites (name, url, alexa, country) VALUES ('DraftB', 'https://b.example/', 101, NULL);"
    )
    distinct_with_null = [
        r[0]
        for r in conn.execute(
            "SELECT DISTINCT country FROM websites ORDER BY country ASC;"
        ).fetchall()
    ]
    count_distinct = conn.execute(
        "SELECT COUNT(DISTINCT country) FROM websites;"
    ).fetchone()[0]
    exp3 = {
        "distinct_rows_including_null": [None, "CN", "USA"],
        "count_distinct_non_null": 2,
    }
    act3 = {
        "distinct_rows_including_null": distinct_with_null,
        "count_distinct_non_null": count_distinct,
    }
    cases.append(
        {
            "name": "select_distinct_with_null_and_count",
            "summary": "验证多个 NULL 在 SELECT DISTINCT 中合并为一行且 COUNT(DISTINCT) 忽略 NULL",
            "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-distinct-lab/explore-distinct.py

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

下载课程关联工程包:SQL

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

下载课程关联工程包:SQL

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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