分页

PostgreSQL 汇总统计与窗口函数

Michel Semaan

Data Scientist

什么是分页?

  • 分页:将数据拆分为(近似)等大小块
  • 用途
    • 许多 API 以"页面"返回数据以减少传输量
    • 按四分位或三分位(上中下 33%)划分以评估表现

使用 NTILE

  • NTILE(n) 将数据分为 n 个近似等大的页面
PostgreSQL 汇总统计与窗口函数

分页 - 源表

查询

SELECT
  DISTINCT Discipline
FROM Summer_Medals;
  • 将数据分为 15 个近似等大的页面
  • 67 / 15 ≃ 4,因此每页含 4 或 5 行

结果

| Discipline          |
|---------------------|
| Wrestling Freestyle |
| Archery             |
| Baseball            |
| Lacrosse            |
| Judo                |
| Athletics           |
| ...                 |

(67 rows)
PostgreSQL 汇总统计与窗口函数

分页

查询

WITH Disciplines AS (
  SELECT
    DISTINCT Discipline
  FROM Summer_Medals)

SELECT
  Discipline, NTILE(15) OVER () AS Page
From Disciplines
ORDER BY Page ASC;

结果

| Discipline          | Page |
|---------------------|------|
| Wrestling Freestyle | 1    |
| Archery             | 1    |
| Baseball            | 1    |
| Lacrosse            | 1    |
| Judo                | 1    |
| Athletics           | 2    |
| ...                 | ...  |
PostgreSQL 汇总统计与窗口函数

上中下三分位

查询

WITH Country_Medals AS (
  SELECT
    Country, COUNT(*) AS Medals
  FROM Summer_Medals
  GROUP BY Country),

SELECT
  Country, Medals,
  NTILE(3) OVER (ORDER BY Medals DESC) AS Third
FROM Country_Medals;

结果

| Country | Medals | Third |
|---------|--------|-------|
| USA     | 4585   | 1     |
| URS     | 2049   | 1     |
| GBR     | 1720   | 1     |
| ...     | ...    | ...   |
| CZE     | 56     | 2     |
| LTU     | 55     | 2     |
| ...     | ...    | ...   |
| DOM     | 6      | 3     |
| BWI     | 5      | 3     |
| ...     | ...    | ...   |
PostgreSQL 汇总统计与窗口函数

三分位均值

查询

WITH Country_Medals AS (...),

  Thirds AS (
  SELECT
    Country, Medals,
    NTILE(3) OVER (ORDER BY Medals DESC) AS Third
  FROM Country_Medals)

SELECT
  Third,
  ROUND(AVG(Medals), 2) AS Avg_Medals
FROM Thirds
GROUP BY Third
ORDER BY Third ASC;

结果

| Third | Avg_Medals |
|-------|------------|
| 1     | 598.74     |
| 2     | 22.98      |
| 3     | 2.08       |
PostgreSQL 汇总统计与窗口函数

Passons à la pratique !

PostgreSQL 汇总统计与窗口函数

Preparing Video For Download...