如何使用标准 SQL 将日期时间转换为 Google Bigquery 中的日期,或者如何从 datetime 的 where 语句中提取年份?

How do I convert a datetime to a date in Google Bigquery using standard SQL or how do I extract the year in a where statement from datetime?

目前我有一个日期时间字段,我需要过滤我的 WHERE 语句,特别是 2019 年和 2020 年。如果我只有一个没有时间的日期字段,我知道我可以使用:

WHERE extract(year from cast([field name] as date))> 2018 

例如提取年份。

因此,我需要两件事之一:

  1. 我需要将日期时间字段转换为日期,以便我可以使用上面的摘录 sql,或者

  2. 我需要一个涉及日期时间字段的 WHERE 语句,它只允许我查看 > 2018 年的数据。

为了将日期时间转换为日期,我尝试了 convert 和 left 函数,此外还有大多数在线的 bigquery 指南解决方案,不幸的是,它们对我不起作用。

这是当前日期时间格式的示例:“2018-08-22 02:48:56”

在此先感谢您的帮助!

Here's an image of the error I get when extracting

我建议不要在被过滤的列上应用日期函数,因为这会给您的数据库带来更多的工作(该列中的每个值都必须在比较之前进行转换),并且会阻止数据库利用现有的指数.

相反,您可以将 datetime 列与文字进行比较,如下所示:

where mydatetimecol >= datetime(2019, 1, 1, 0, 0, 0)

如果你有未来的日期,那么你可以使用半开间隔来做检查:

where 
    mydatetimecol >= datetime(2019, 1, 1, 0, 0, 0)
    and mydatetimecol < datetime(2021, 1, 1, 0, 0, 0)

您似乎将日期存储为 YYYY-MM-DD HH:MI:SS 格式的字符串。如果是这样,您可以改为进行字符串比较(幸运的是,这种格式允许这样做):

where 
    mydatetimecol >= '2019-01-01 00:00:00'
    and mydatetimecol < '2021-01-01 00:00:00'

为什么不直接使用这个?

WHERE col >= datetime('2019-01-01')

或:

WHERE col >= datetime('2019-01-01') and col < datetime('2021-01-01')

如果您将值存储为字符串,那么您很幸运,因为您可以只使用字符串比较:

WHERE col >= '2019-01-01' and col < '2021-01-01'

但是,我建议您使用正确的数据类型加载数据。