聚合

BigQuery 入门

Matthew Forrest

Field CTO

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         |
  • 汇总大型数据集
  • 识别趋势与模式
  • BigQuery 对聚合进行了优化
BigQuery 入门

GROUP BY 与 ORDER BY

SELECT
  -- 稍后按 order_id 分组 
  order_id,
  SUM(sales) AS order_total
FROM total_sales
-- 在此对查询进行分组和排序
GROUP BY order_id
ORDER BY order_total DESC;
| order_id | order_total |
|----------|-------------|
| 1        | 500         |
| 2        | 850         |
BigQuery 入门

COUNT

SELECT
  category,
  -- 统计返回的行数
  COUNT(order_id) AS record_count
FROM total_sales
GROUP BY category;
| category    | record_count |
|-------------|--------------|
| shoes       | 238          |
| electronics | 183          |
BigQuery 入门

SUM 与 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       |
BigQuery 入门

MIN 与 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 |
BigQuery 入门

COUNTIF

SELECT
  category,
  -- 仅在 cost 大于 500 时计数 
  COUNTIF(cost > 500) AS large_items
FROM total_sales
GROUP BY category;
| category    | large_items |
|-------------|-------------|
| shoes       | 2           |
| electronics | 35          |
BigQuery 入门

HAVING 子句

SELECT
category,
COUNT(order_id) as orders
FROM total_sales
-- 仅保留平均 cost 大于 75 美元的品类
HAVING AVG(cost) > 75;
| category    | orders |
|-------------|--------|
| shoes       | 25     |
| electronics | 98     |
BigQuery 入门

ANY_VALUE

SELECT
  order_id,
  -- 返回任意一个 category
  ANY_VALUE(category) as cat
  -- 返回最高 cost 对应的 category
  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    |
BigQuery 入门

Passons à la pratique !

BigQuery 入门

Preparing Video For Download...