带有 UNNEST、LEFT JOIN 和 WHERE 语句的 Bigquery
Posted
技术标签:
【中文标题】带有 UNNEST、LEFT JOIN 和 WHERE 语句的 Bigquery【英文标题】:Bigquery with UNNEST, LEFT JOIN and WHERE statement 【发布时间】:2018-12-18 21:14:43 【问题描述】:以下带有 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'
添加到 unnest 中,以便我的 WHERE 获得 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
如您所见 - 我只是将过滤逻辑移到子选择中
【讨论】:
以上是关于带有 UNNEST、LEFT JOIN 和 WHERE 语句的 Bigquery的主要内容,如果未能解决你的问题,请参考以下文章
带有 LEFT JOIN 和 IF 语句的有限 GROUP_CONCAT
带有 LEFT JOIN 和 MAX 的 LibreOffice HSQLDB WHERE 子句?
带有 LEFT JOIN 和 GROUP BY 的 COUNT(*) 在 MySQL 中包含 NULL