【问题标题】:BigQuery Standard SQL returns different WEEK from timestampBigQuery 标准 SQL 从时间戳返回不同的 WEEK
【发布时间】:2019-04-13 21:15:52
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案1】:

    这有点微妙,但旧版 SQL 和标准 SQL 处理数周的方式不同。 In Legacy SQL:

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

    In Standard SQL:

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

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

    【讨论】:

    • 虽然这可能是一个愚蠢的问题,但有没有更“正确”的定义?我希望从代码库中删除旧版 SQL。我相信 ISOWEEK 更适合我的目的 第 1-53 周对于队列报告更有意义,但我需要证明数据差异是合理的。
    • 如果满足您的需要,请使用 ISOWEEK。至少它是一个已定义的标准,并且会随着时间的推移和跨平台保持一致。
    猜你喜欢
    • 2022-07-12
    • 2017-04-30
    • 1970-01-01
    • 2017-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-08
    • 2014-10-03
    相关资源
    最近更新 更多