BigQuery Standard SQL从时间戳返回不同的WEEK

时间:2018-11-10 15:18:43

标签: sql google-bigquery unix-timestamp standard-sql

我正在将旧查询从“旧版SQL”转换为“标准SQL”,并注意到我的报告已关闭。我将其追溯到传统SQL和标准SQL,它们根据UNIX毫秒时间戳返回不同的星期。

我对旧版SQL查询的印象是正确的,但是,我很想知道两者之间的区别。并非所有星期都如此,但足以使我的报告大打折扣。

这是一个例子:

#legacySQL
SELECT WEEK(MSEC_TO_TIMESTAMP(1470631859000)) AS sign_up_week;

输出:33

#standardSQL
SELECT EXTRACT(WEEK FROM TIMESTAMP_MILLIS(1470631859000));

输出:32

我已经查看了旧版SQL参考上的以下文档:

WEEK(<timestamp>)
Returns the week of a TIMESTAMP data type as an integer between 1 and 53, inclusively.

Weeks begin on Sunday, so if January 1 is on a day other than Sunday, week 1 has fewer than 7 days and the first Sunday of the year is the first day of week 2.

并且来自标准SQL参考:

WEEK(<WEEKDAY>): Returns the week number of the date in the range [0, 53]. Weeks begin on WEEKDAY. Dates prior to the first WEEKDAY of the year are in week 0. Valid values for WEEKDAY are SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, and SATURDAY.

ISOWEEK: Returns the ISO 8601 week number of the date_expression. ISOWEEKs begin on Monday. Return values are in the range [1, 53]. The first ISOWEEK of each ISO year begins on the Monday before the first Thursday of the Gregorian calendar year.

如何获取标准SQL查询以输出与旧版SQL查询相同的星期数?如果不是,哪个星期正确?看来我没有办法让他们在本质上与之吻合。

1 个答案:

答案 0 :(得分:2)

这有点微妙,但是旧版和标准SQL处理周的时间却有所不同。 In Legacy SQL

  

一周从星期日开始,因此,如果1月1日不是星期日,则第1周少于7天,而一年中的第一个星期日是第2周的第一天。

In Standard SQL:

  
      
  • WEEK:返回日期的星期数,范围为[0,53]。星期从星期日开始,而一年中第一个星期日之前的日期在星期0。
  •   

因此,在旧版SQL中,第一个星期日是第2周。在Standard SQL中,第一个星期日是第1周。