BigQuery 的特殊聚合

BigQuery 入门

Matthew Forrest

Field CTO

特殊聚合简介

Function Category Description
APPROX_COUNT_DISTINCT, APPROX_QUANTILES, APPROX_TOP_COUNT, APPROX_TOP_SUM 近似聚合 为特定计算提供估计值,减少处理时间与资源占用。
ARRAY_CONCAT_AGG, STRING_AGG 数组与字符串处理 收集、连接并处理数组与字符串。
LOGICAL_AND, LOGICAL_OR 逻辑运算 对一组布尔表达式执行 AND 与 OR 运算。
BigQuery 入门

ARRAY_CONCAT_AGG

  • ARRAY_CONCAT_AGG() 解决 ARRAY_AGG() 的限制
SELECT
  order_id,
  ARRAY_CONCAT_AGG(order_items) AS all_items
FROM sales_data
GROUP BY order_id;
| order_id | all_items                          |
|----------|------------------------------------|
| 1        | [shoes, electronics]               |
| 2        | [electronics, household, clothing] |
BigQuery 入门

STRING_AGG

  • STRING_AGG() 将多字符串连接为单个字符串
SELECT STRING_AGG(customer_id, ', ') AS all_customers
FROM sales_data
WHERE delivery_date 
BETWEEN CURRENT_TIMESTAMP() 
AND TIMESTAMP_ADD(CURRENT_TIMESTAMP(), INTERVAL 3 DAY) ;
| all_customers   |
|-----------------|
| 123, 456, 789   |
BigQuery 入门

APPROX_COUNT_DISTINCT

  • APPROX_COUNT_DISTINCT() 快速估计不同值的数量
SELECT
  customer_id,
  APPROX_COUNT_DISTINCT(order_id) AS unique_orders
FROM sales_data
GROUP BY customer_id;
| customer_id | unique_orders |
|-------------|---------------|
| 1           | 5             |
| 2           | 2             |
BigQuery 入门

APPROX_QUANTILES

  • APPROX_QUANTILES() 返回近似分位数
SELECT
  category,
  APPROX_QUANTILES(value, 4) AS quartiles
FROM sales_data
GROUP BY category;
| category    | quartiles         |
|-------------|-------------------|
| shoes       | [25, 40, 55, 100] |
| electronics | [10, 40, 95, 300] |
BigQuery 入门

APPROX_TOP_COUNT

  • APPROX_TOP_COUNT() 按出现次数查找前 K 个元素
SELECT
  category,
  APPROX_TOP_COUNT(customer_id, 3) AS customers
FROM sales_data
GROUP BY category;
| category    | customers   |
|-------------|-------------|
| shoes       | [1, 7, 19]  |
| electronics | [8, 19, 22] |
BigQuery 入门

APPROX_TOP_SUM

  • APPROX_TOP_SUM(el, weight, K) 基于 weight 找到元素 el 的前 K
SELECT
  seller_id,
  APPROX_TOP_SUM(item_id, cost, 3) AS top_items
FROM sales_data
GROUP BY seller_id;
| seller_id | top_items                                    |
|-----------|----------------------------------------------|
| 1         | [[1024, 5000], [1567, 3000], [3489, 2000]]   |
| 2         | [[5647, 6500], [9867, 3500], [1074, 2100]]   |
BigQuery 入门

LOGICAL_AND 与 LOGICAL_OR

SELECT
  customer_id,
  -- 若全部为 true,则为 true
  LOGICAL_AND(order_status = 'shipped') AS all_shipped,
  -- 若至少一个为 true,则为 true
  LOGICAL_OR(order_status = 'shipped') AS one_shipped
FROM sales_data
GROUP BY customer_id;
| customer_id | all_shipped | one_shipped |
|-------------|-------------|-------------|
| 1           | false       | true        |
| 2           | true        | true        |
BigQuery 入门

Vamos praticar!

BigQuery 入门

Preparing Video For Download...