Funzioni WINDOW

Introduzione a BigQuery

Matthew Forrest

Field CTO

Cosa sono le funzioni WINDOW

Un'illustrazione di una WINDOW con una SUM mobile

Introduzione a BigQuery

Quando usare le funzioni WINDOW

Funzioni WINDOW raggruppate per tipo

1 https://towardsdatascience.com/a-guide-to-advanced-sql-window-functions-f63f2642cbf9
Introduzione a BigQuery

Struttura WINDOW, PARTITION e ORDER BY

SELECT
  customer_id,
  order_date,
  order_total,
  ROW_NUMBER() OVER(

PARTITION BY customer_id
ORDER BY order_date
) AS order_sequence FROM orders;
  • ROW_NUMBER(): La funzione window che restituisce il numero di riga
  • OVER(): Definisce il frame della finestra
  • PARTITION BY customer_id: Raggruppa i dati per cliente
  • ORDER BY order_date: Ordina i dati dentro ogni partizione
  • order_sequence: Risultato dell'operazione della funzione window
Introduzione a BigQuery

RANK e PERCENT_RANK

SELECT
  product_id,
  product_photos_qty,
  -- Ordinal rank for each row
  RANK() OVER(
    ORDER BY product_photos_qty DESC
  ) as rank,
  -- Percentile rank for each row
  PERCENT_RANK() OVER(
    ORDER BY product_photos_qty
  ) as percent
FROM ecommerce.ecomm_products 
ORDER BY product_photos_qty DESC;

Risultati della query con RANK e PERCENT_RANK

Introduzione a BigQuery

LAG e LEAD

SELECT
  product_id,
  -- Returns value from previous row
  LAG(product_photos_qty) OVER(
    ORDER BY product_photos_qty
  ) as lag,
  product_photos_qty,
  -- Returns value from next row
  LEAD(product_photos_qty) OVER(
    ORDER BY product_photos_qty
  ) as lead
FROM ecommerce.ecomm_products 
ORDER BY product_photos_qty DESC;

Immagine che mostra LAG e LEAD nei risultati della query

Introduzione a BigQuery

RANGE BETWEEN e CURRENT ROW

SELECT
  order_id,
  order_timestamp,
  SUM(cost) OVER(
    ORDER BY order_timestamp 
    ROWS BETWEEN 2 PRECEDING 
    AND CURRENT ROW) as rolling_avg
FROM sales_data
ORDER BY order_timestamp

Opzioni di delimitazione basate su righe:

  • UNBOUNDED PRECEDING: Tutte le righe precedenti
  • UNBOUNDED FOLLOWING: Tutte le righe successive
  • [INT] ROWS PRECEDING: Numero specifico di righe precedenti
  • [INT] ROWS FOLLOWING: Numero specifico di righe successive
Introduzione a BigQuery

QUALIFY

SELECT
  product_id,
  product_photos_qty,
  RANK() OVER(
    ORDER BY product_photos_qty DESC
  ) as rank
FROM ecommerce.ecomm_products 
-- Filter using QUALIFY
QUALIFY rank < 4
ORDER BY product_photos_qty DESC;

Risultati della query che usa QUALIFY per trovare valori con rank pari a 3 o superiore

  • Non puoi usare HAVING perché non stai aggregando
Introduzione a BigQuery

Esercitiamoci!

Introduzione a BigQuery

Preparing Video For Download...