如何在Google BigQuery中填写缺少的日期

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (10)

我想写一个图表,显示firebase中的活跃用户

我写了这段代码

SELECT event_date, COUNT(DISTINCT user_pseudo_id) AS user_count
FROM `mark-3314e.analytics_197261162.events_*`  
WHERE _TABLE_SUFFIX BETWEEN FORMAT_DATE('%Y%m%d', DATE_SUB(CURRENT_DATE(), INTERVAL 7 DAY)) AND FORMAT_DATE('%Y%m%d', CURRENT_DATE())
AND event_name = 'session_start'
GROUP BY event_date
ORDER BY event_date ASC

这就是回应

Row event_date  user_count  
1   20190617        1
2   20190621        3

有没有办法用以前的数据填补21和17之间的缺失日期?喜欢:

event_date  user_count  
20190617        1
20190618        1
20190619        1
20190620        1
20190621        3
提问于
用户回答回答于

这是使用GENERATE_DATE_ARRAYBigQuery中的函数的可能解决方案。

with data as (
   SELECT parse_date('%Y%m%d', event_date) AS event_date, COUNT(DISTINCT user_pseudo_id) AS user_count
   FROM `mark-3314e.analytics_197261162.events_*`  
   WHERE _TABLE_SUFFIX BETWEEN FORMAT_DATE('%Y%m%d', DATE_SUB(CURRENT_DATE(), INTERVAL 7 DAY)) AND FORMAT_DATE('%Y%m%d', CURRENT_DATE())
   AND event_name = 'session_start'
   GROUP BY event_date
   ORDER BY event_date ASC
)

select dt as event_date, user_count from (
  select user_count,
      if(
        previousdate is null, 
        generate_date_array(date, date_sub(nextdate, interval 1 day), interval 1 day), 
        generate_date_array(date, if(nextdate is null, date, date_sub(nextdate, interval 1 day)), interval 1 day)
      ) as dates 
  from (
          select 
            lag(event_date) over(order by event_date) as previousdate,
            event_date as date,
            lead(event_date) over(order by event_date) as nextdate,
            user_count
          from data
      )
), unnest(dates) dt
用户回答回答于

您可以加入包含感兴趣的完整日期范围的日历表:

WITH dates AS (
    SELECT '20190617' AS dt UNION ALL
    SELECT '20190618' UNION ALL
    SELECT '20190619' UNION ALL
    SELECT '20190620' UNION ALL
    SELECT '20190621'
)

SELECT
    t1.dt AS event_date,
    COUNT(DISTINCT t2.user_pseudo_id) AS user_count
FROM dates t1
LEFT JOIN `mark-3314e.analytics_197261162.events_*` t2
    ON t1.dt = t2.event_date AND
       t2._TABLE_SUFFIX BETWEEN FORMAT_DATE('%Y%m%d', DATE_SUB(CURRENT_DATE(), INTERVAL 7 DAY)) AND FORMAT_DATE('%Y%m%d', CURRENT_DATE())
       AND t2.event_name = 'session_start'
GROUP BY
    t1.dt
ORDER BY
    t1.dt;

有关在BigQuery中生成日期范围的更一般方法,请参阅此SO问题

所属标签

可能回答问题的人

  • 学生

    3 粉丝476 提问7 回答
  • uncle_light

    5 粉丝518 提问6 回答
  • 最爱开车啦

    8 粉丝503 提问5 回答
  • 骑牛看晨曦

    4 粉丝522 提问5 回答

扫码关注云+社区

领取腾讯云代金券