使用BigQuery对日期数组执行子查询

时间:2018-07-11 08:36:24

标签: google-bigquery subquery

我有一个存储销售目标的表-这些目标通常是按月设置,但按天输入-这意味着每日目标是月份目标除以天数。

这是输入目标的劳动密集型方法,因此我想重新创建带有开始日期和结束日期的表:

WITH targets AS (
  SELECT DATE '2018-01-01' AS dateStart, DATE '2018-01-31' AS dateEnd, 'uk' AS market, NUMERIC '1550' AS quantity
  UNION ALL SELECT '2018-02-01', '2018-02-28', "uk", 560
)

在我的查询中,我需要生成一个日期数组(dateStartdateEnd),然后针对该数组中的每个日期,应用市场并将目标除以该数组中的日期数-但我无法正常运作。我正在寻找类似的东西:

SELECT 
  *,
  (SELECT market FROM targets WHERE dr IN GENERATE_DATE_ARRAY(targets.dateStart, targets.dateEnd, INTERVAL 1 DAY)) AS market,
  (SELECT SAFE_DIVIDE(budget, COUNT(GENERATE_DATE_ARRAY(targets.dateStart, targets.dateEnd, INTERVAL 1 DAY)) FROM targets WHERE dr IN GENERATE_DATE_ARRAY(targets.dateStart, targets.dateEnd, INTERVAL 1 DAY)) AND targets.market = market AS budget
FROM UNNEST(GENERATE_DATE_ARRAY(targets.dateStart, targets.dateEnd, INTERVAL 1 DAY)) AS dr

这意味着更少的数据输入和更少的源表中的行(这是一个Google表格,因此最终将达到限制)。感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

以下是用于BigQuery标准SQL

  
#standardSQL
WITH targets AS (
  SELECT DATE '2018-01-01' AS dateStart, DATE '2018-01-31' AS dateEnd, 'uk' AS market, NUMERIC '1550' AS quantity
  UNION ALL SELECT '2018-02-01', '2018-02-28', "uk", 560
)
SELECT market, day, quantity / days AS target
FROM targets, 
  UNNEST(GENERATE_DATE_ARRAY(dateStart, dateEnd)) day, 
  UNNEST([DATE_DIFF(dateEnd, dateStart, DAY) + 1]) days
ORDER BY market, day