带有UNNEST,LEFT JOIN和WHERE语句的Bigquery

时间:2018-12-18 21:14:43

标签: sql google-bigquery

以下带有UNNEST和LEFT JOIN的查询添加带有日期的空“ 0”行:

   SELECT cal_day, count(e.datetime) AS cnt
    FROM UNNEST(
        GENERATE_DATE_ARRAY(DATE('2018-12-10'), CURRENT_DATE(), INTERVAL 1 DAY)
    )  AS cal_day
    LEFT JOIN `eventlogs`  e
      ON cal_day = CAST( TIMESTAMP_MICROS( CAST(CAST(e.datetime AS NUMERIC)*1000 AS INT64)) AS DATE)
    # WHERE ( CAST(datetime AS NUMERIC) > 1544375081371.431 ) AND message LIKE '%mymessage%' 
    GROUP BY cal_day 
    ORDER BY cal_day
    LIMIT 10000

导致:

1   2018-12-10 00:00:00 UTC 561
2   2018-12-11 00:00:00 UTC 1473
3   2018-12-12 00:00:00 UTC 650
4   2018-12-13 00:00:00 UTC 407
5   2018-12-14 00:00:00 UTC 283
6   2018-12-15 00:00:00 UTC 1
6   2018-12-16 00:00:00 UTC 0
7   2018-12-17 00:00:00 UTC 213
8   2018-12-18 00:00:00 UTC 583

当我添加WHERE子句时,情况并非如此。如何将message='mymessage'添加到嵌套中,以便在WHERE中获得0个计数日期?

1 个答案:

答案 0 :(得分:1)

#standardSQL
SELECT cal_day, IFNULL(cnt, 0) AS cnt 
FROM UNNEST(
    GENERATE_DATE_ARRAY(DATE('2018-12-10'), CURRENT_DATE(), INTERVAL 1 DAY)
)  AS cal_day
LEFT JOIN (
  SELECT 
    CAST( TIMESTAMP_MICROS( CAST(CAST(datetime AS NUMERIC)*1000 AS INT64)) AS DATE) AS day, 
    COUNT(datetime) AS cnt 
  FROM `eventlogs`
  WHERE (CAST(datetime AS NUMERIC) > 1544375081371.431 ) 
  AND message LIKE '%mymessage%' 
  GROUP BY day 
) e
ON cal_day = e.day
ORDER BY cal_day
LIMIT 10000   

如您所见-我只是将过滤逻辑移到了subselect内