分頁

PostgreSQL 統計摘要與視窗函式

Michel Semaan

Data Scientist

什麼是分頁?

  • 分頁(Paging):把資料切成(大致)等大的區塊
  • 用途
    • 很多 API 會用「頁」回傳資料,以減少傳輸量
    • 依四分位或三等分(前 33%、中間、後段)劃分資料來評估表現

認識 NTILE

  • NTILE(n) 會把資料切成 n 個大致相等的頁面
PostgreSQL 統計摘要與視窗函式

分頁-來源資料表

查詢

SELECT
  DISTINCT Discipline
FROM Summer_Medals;
  • 將資料切成約 15 個等大的頁面
  • $67 / 15 \simeq 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 統計摘要與視窗函式

一起來練習吧!

PostgreSQL 統計摘要與視窗函式

Preparing Video For Download...