Agrégations

Introduction à BigQuery

Matthew Forrest

Field CTO

Agrégations dans BigQuery

SELECT
  SUM(sales) AS total_sales,
  AVG(quantity) AS avg_quantity,
  MAX(price) AS max_price,
  MIN(price) AS min_price
FROM sales_data;
| total_sales | avg_quantity | max_price | min_price |
|-------------|--------------|-----------|-----------|
| 50          | 8            | 100       | 2         |
  • Résumer de grands ensembles de données
  • Repérer des tendances et des motifs
  • BigQuery est optimisé pour les agrégations
Introduction à BigQuery

GROUP BY et ORDER BY

SELECT
  -- Plus loin, nous regrouperons par la colonne 'order_id' 
  order_id,
  SUM(sales) AS order_total
FROM total_sales
-- Ici, nous pouvons GROUP et ORDER la requête
GROUP BY order_id
ORDER BY order_total DESC;
| order_id | order_total |
|----------|-------------|
| 1        | 500         |
| 2        | 850         |
Introduction à BigQuery

COUNT

SELECT
  category,
  -- COUNT le nombre de lignes renvoyées
  COUNT(order_id) AS record_count
FROM total_sales
GROUP BY category;
| category    | record_count |
|-------------|--------------|
| shoes       | 238          |
| electronics | 183          |
Introduction à BigQuery

SUM et AVG

SELECT
  category,
  SUM(cost) AS total_cost,
  AVG(cost) AS average_payment
FROM total_sales
GROUP BY category;
| category    | total_cost | avg_cost |
|-------------|------------|----------|
| shoes       | 10345      | 54       |
| electronics | 9340       | 34       |
Introduction à BigQuery

MIN et MAX

SELECT
    MIN(product_photos_qty) as min_photo_count,
    MAX(product_photos_qty) as max_photo_count
FROM ecommerce.ecomm_products;
| min__photo_count | max__photo_count |
|----------|----------|
| 1    | 20 |
Introduction à BigQuery

COUNTIF

SELECT
  category,
  -- Compte seulement si le coût dépasse 500 $
  COUNTIF(cost > 500) AS large_items
FROM total_sales
GROUP BY category;
| category    | large_items |
|-------------|-------------|
| shoes       | 2           |
| electronics | 35          |
Introduction à BigQuery

HAVING

SELECT
category,
COUNT(order_id) as orders
FROM total_sales
-- Ici, on ajoute la condition pour les catégories dont le coût moyen dépasse 75 $
HAVING AVG(cost) > 75;
| category    | orders |
|-------------|--------|
| shoes       | 25     |
| electronics | 98     |
Introduction à BigQuery

ANY_VALUE

SELECT
  order_id,
  -- Retourne une catégorie arbitraire
  ANY_VALUE(category) as cat
  -- Retourne la catégorie avec le coût le plus élevé
  ANY_VALUE(category HAVING MAX cost) AS max_cat
FROM total_sales
GROUP BY order_id;
| order_id | cat       | max_cat     |
|----------|-----------|-------------|
| 1        | shoes     | electronics |
| 2        | household | exercise    |
Introduction à BigQuery

Passons à la pratique !

Introduction à BigQuery

Preparing Video For Download...