自动转换日期以格式化 YYWW
Automatizing conversion dates to format YYWW
我需要将 2016 年最后一周 的所有天按日期转换为 YYYYWW
格式。
#standardSQL
WITH Input AS (
SELECT date
FROM UNNEST([
DATE '2016-12-26',
DATE '2016-12-27',
DATE '2016-12-28',
DATE '2016-12-29',
DATE '2016-12-30',
DATE '2016-12-31',
DATE '2017-01-01']) AS date
)
SELECT
date,
CAST(FORMAT_DATE('%Y%V', CAST(date AS DATE)) AS STRING) AS YearWeek,
CAST(FORMAT_DATE('%Y', CAST(date AS DATE)) AS STRING) AS Year,
CAST(FORMAT_DATE('%V', CAST(date AS DATE)) AS STRING) AS
FROM Input
ORDER BY date
一切正常,直到达到 2017-01-01
:
Row date YearWeek Year Week
1 2016-12-26 201652 2016 52
2 2016-12-27 201652 2016 52
3 2016-12-28 201652 2016 52
4 2016-12-29 201652 2016 52
5 2016-12-30 201652 2016 52
6 2016-12-31 201652 2016 52
7 2017-01-01 201752 2017 52
'201752
' 应该是 '201652
'。
为历史日期自动化的最佳方式?
像这样:
IF (REGEXP_EXTRACT(date,r'\d{4}-\d{2}-(\d{2})') = CAST('01' AS STRING)
AND Week = CAST('52' AS STRING), Year-1, Year)
%Y
将 return 日期的日历年而不是 ISO 年。对于 return ISO 年份,即 2017 年 1 月 1 日为 2016 年,请改用 %G
。另见 Supported Format Elements for DATE。
以下适用于 BigQuery 标准 SQL
#standardSQL
WITH Input AS (
SELECT DATE
FROM UNNEST([
DATE '2016-12-26',
DATE '2016-12-27',
DATE '2016-12-28',
DATE '2016-12-29',
DATE '2016-12-30',
DATE '2016-12-31',
DATE '2017-01-01']) AS date
)
SELECT
date,
FORMAT_DATE('%G%V', date) AS YearWeek
FROM Input
ORDER BY date
另请注意 - 在您的示例中:
1. 你不需要 CAST(date AS DATE)
因为 date
已经是 DATE
类型
2. 你不需要 CAST(FORMAT_DATE(...) AS STRING)
因为 FORMAT_DATE
已经 returns STRING
我需要将 2016 年最后一周 的所有天按日期转换为 YYYYWW
格式。
#standardSQL
WITH Input AS (
SELECT date
FROM UNNEST([
DATE '2016-12-26',
DATE '2016-12-27',
DATE '2016-12-28',
DATE '2016-12-29',
DATE '2016-12-30',
DATE '2016-12-31',
DATE '2017-01-01']) AS date
)
SELECT
date,
CAST(FORMAT_DATE('%Y%V', CAST(date AS DATE)) AS STRING) AS YearWeek,
CAST(FORMAT_DATE('%Y', CAST(date AS DATE)) AS STRING) AS Year,
CAST(FORMAT_DATE('%V', CAST(date AS DATE)) AS STRING) AS
FROM Input
ORDER BY date
一切正常,直到达到 2017-01-01
:
Row date YearWeek Year Week
1 2016-12-26 201652 2016 52
2 2016-12-27 201652 2016 52
3 2016-12-28 201652 2016 52
4 2016-12-29 201652 2016 52
5 2016-12-30 201652 2016 52
6 2016-12-31 201652 2016 52
7 2017-01-01 201752 2017 52
'201752
' 应该是 '201652
'。
为历史日期自动化的最佳方式?
像这样:
IF (REGEXP_EXTRACT(date,r'\d{4}-\d{2}-(\d{2})') = CAST('01' AS STRING)
AND Week = CAST('52' AS STRING), Year-1, Year)
%Y
将 return 日期的日历年而不是 ISO 年。对于 return ISO 年份,即 2017 年 1 月 1 日为 2016 年,请改用 %G
。另见 Supported Format Elements for DATE。
以下适用于 BigQuery 标准 SQL
#standardSQL
WITH Input AS (
SELECT DATE
FROM UNNEST([
DATE '2016-12-26',
DATE '2016-12-27',
DATE '2016-12-28',
DATE '2016-12-29',
DATE '2016-12-30',
DATE '2016-12-31',
DATE '2017-01-01']) AS date
)
SELECT
date,
FORMAT_DATE('%G%V', date) AS YearWeek
FROM Input
ORDER BY date
另请注意 - 在您的示例中:
1. 你不需要 CAST(date AS DATE)
因为 date
已经是 DATE
类型
2. 你不需要 CAST(FORMAT_DATE(...) AS STRING)
因为 FORMAT_DATE
已经 returns STRING