首页 > 解决方案 > BigQuery 标准 SQL 从时间戳返回不同的 WEEK

问题描述

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

我的印象是 Legacy SQL 查询是正确的,但是,我很想知道其中的区别。这不是持续数周,但足以让我的报告大失所望。

这是一个例子:

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

输出:33

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

输出:32

我查看了有关 Legacy 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 查询相同的周数?如果不是,哪个周数是正确的?看来我不能让他们自然地相吻合。

标签: sqlgoogle-bigqueryunix-timestampbigquery-standard-sql

解决方案


这有点微妙,但旧版 SQL 和标准 SQL 处理几周的方式不同。 在旧版 SQL 中

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

在标准 SQL 中:

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

因此,在 Legacy SQL 中,第一个星期日是第 2 周。在标准 SQL 中,第一个星期日是第 1 周。


推荐阅读