Paging

PostgreSQL: Zusammenfassende Statistiken und Fensterfunktionen

Michel Semaan

Data Scientist

Was ist Paging?

  • Paging: Daten in (ungefähr) gleiche Teile aufteilen
  • Anwendungsfälle
    • Viele APIs schicken Daten in „Pages“, um Datenmenge zu reduzieren
    • Aufteilung der Daten in Quartile oder Drittel (oberes, mittleres, unteres Drittel), um Leistung zu bewerten

Verwende NTILE

  • NTILE(n) teilt die Daten in n ungefähr gleich große Seiten auf
PostgreSQL: Zusammenfassende Statistiken und Fensterfunktionen

Paging – Quelltabelle

Abfrage

SELECT
  DISTINCT Discipline
FROM Summer_Medals;
  • Teile die Daten in 15 ungefähr gleich große Seiten auf
  • $67 / 15 \simeq 4$, also hat jede Seite vier oder fünf Zeilen

Ergebnis

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

(67 rows)
PostgreSQL: Zusammenfassende Statistiken und Fensterfunktionen

Paging

Abfrage

WITH Disciplines AS (
  SELECT
    DISTINCT Discipline
  FROM Summer_Medals)

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

Ergebnis

| Discipline          | Page |
|---------------------|------|
| Wrestling Freestyle | 1    |
| Archery             | 1    |
| Baseball            | 1    |
| Lacrosse            | 1    |
| Judo                | 1    |
| Athletics           | 2    |
| ...                 | ...  |
PostgreSQL: Zusammenfassende Statistiken und Fensterfunktionen

Oberes, mittleres und unteres Drittel

Abfrage

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;

Ergebnis

| 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: Zusammenfassende Statistiken und Fensterfunktionen

Durchschnitte der Drittel

Abfrage

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;

Ergebnis

| Third | Avg_Medals |
|-------|------------|
| 1     | 598.74     |
| 2     | 22.98      |
| 3     | 2.08       |
PostgreSQL: Zusammenfassende Statistiken und Fensterfunktionen

Lass uns üben!

PostgreSQL: Zusammenfassende Statistiken und Fensterfunktionen

Preparing Video For Download...