从 Bigquery 中的时间戳中提取日期:一种更可取的方法

Extracting date from timestamp in Bigquery: a preferable method

向 Bigquery 专家提问。

这里有两种使用标准 SQL 从 Bigquery 中的时间戳中提取日期的方法

#standardSQL
#1
DATE(TIMESTAMP_MILLIS(CAST((timestamp) AS INT64)))
#2
EXTRACT(DATE FROM TIMESTAMP_MILLIS(timestamp))

哪个更好,为什么?谢谢!

这完全取决于个人喜好;一个并不优于另一个,因为它们具有相同的语义和性能。赞成使用 EXTRACT 的论点是,如果您要提取 select 列表中的其他 date/time 部分,它会镜像它们。例如:

SELECT
  EXTRACT(DATE FROM TIMESTAMP_MILLIS(timestamp)) AS date,
  EXTRACT(ISOYEAR FROM TIMESTAMP_MILLIS(timestamp)) AS iso_year,
  EXTRACT(ISOWEEK FROM TIMESTAMP_MILLIS(timestamp)) AS iso_week
FROM YourTable;

相比于:

SELECT
  DATE(TIMESTAMP_MILLIS(timestamp)) AS date,
  EXTRACT(ISOYEAR FROM TIMESTAMP_MILLIS(timestamp)) AS iso_year,
  EXTRACT(ISOWEEK FROM TIMESTAMP_MILLIS(timestamp)) AS iso_week
FROM YourTable;