Un repaso a las funciones útiles

Estadísticas resumidas y funciones de ventana de PostgreSQL

Michel Semaan

Data Scientist

Nulos a la vista

Consulta

SELECT
  Country, Medal, COUNT(*) AS Awards
FROM summer_medals
WHERE
  Year = 2008 AND Country IN ('CHN', 'RUS')
GROUP BY ROLLUP(Country, Medal)
ORDER BY Country ASC, Medal ASC;
  • null son los totales del grupo

Resultado

| Country | Medal  | Awards |
|---------|--------|--------|
| CHN     | Bronze | 57     |
| CHN     | Gold   | 74     |
| CHN     | Silver | 53     |
| CHN     | null   | 184    |
| RUS     | Bronze | 56     |
| RUS     | Gold   | 43     |
| RUS     | Silver | 44     |
| RUS     | null   | 143    |
| null    | null   | 327    |
Estadísticas resumidas y funciones de ventana de PostgreSQL

Introduce COALESCE

  • COALESCE() toma una lista de valores y devuelve el primer valor no null, de izquierda a derecha.
  • COALESCE(null, null, 1, null, 2) → 1
  • Útil cuando se utilizan operaciones SQL que devuelven null.
    • ROLLUP y CUBE
    • Pivotar
    • LAG y LEAD
Estadísticas resumidas y funciones de ventana de PostgreSQL

Aniquilar nulos

Consulta

SELECT
  COALESCE(Country, 'Both countries') AS Country,
  COALESCE(Medal, 'All medals') AS Medal,
  COUNT(*) AS Awards
FROM summer_medals
WHERE
  Year = 2008 AND Country IN ('CHN', 'RUS')
GROUP BY ROLLUP(Country, Medal)
ORDER BY Country ASC, Medal ASC;

Resultado

| Country        | Medal      | Awards |
|----------------|------------|--------|
| Both countries | All medals | 327    |
| CHN            | All medals | 184    |
| CHN            | Bronze     | 57     |
| CHN            | Gold       | 74     |
| CHN            | Silver     | 53     |
| RUS            | All medals | 143    |
| RUS            | Bronze     | 56     |
| RUS            | Gold       | 43     |
| RUS            | Silver     | 44     |
Estadísticas resumidas y funciones de ventana de PostgreSQL

Comprimir datos

Antes

| Country | Rank |
|---------|------|
| CHN     | 1    |
| RUS     | 2    |
| USA     | 3    |
  • Rank es redundante porque la clasificación está implícita.

Después

CHN, RUS, USA
  • Conciso y proporciona toda la información necesaria, ya que la clasificación está implícita.
Estadísticas resumidas y funciones de ventana de PostgreSQL

Introduce STRING_AGG

  • STRING_AGG(column, separator) toma todos los valores de una columna y los concatena, con separator entre cada valor.

STRING_AGG(Letter, ', ') transforma esto...

| Letter |
|--------|
| A      |
| B      |
| C      |

...en esto

A, B, C
Estadísticas resumidas y funciones de ventana de PostgreSQL

Consulta y resultado

Antes

WITH Country_Medals AS (
  SELECT
    Country, COUNT(*) AS Medals
  FROM Summer_Medals
  WHERE Year = 2012
    AND Country IN ('CHN', 'RUS', 'USA')
    AND Medal = 'Gold'
    AND Sport = 'Gymnastics'
  GROUP BY Country),

  SELECT
    Country,
    RANK() OVER (ORDER BY Medals DESC) AS Rank
  FROM Country_Medals
  ORDER BY Rank ASC;

Después

WITH Country_Medals AS (...),

  Country_Ranks AS (...)

  SELECT STRING_AGG(Country, ', ')
  FROM Country_Medals;

Resultado

CHN, RUS, USA
Estadísticas resumidas y funciones de ventana de PostgreSQL

¡Vamos a practicar!

Estadísticas resumidas y funciones de ventana de PostgreSQL

Preparing Video For Download...