自动化转换日期以格式化YYWW

时间:2017-07-18 12:30:54

标签: google-bigquery standard-sql

我需要将日期从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)

2 个答案:

答案 0 :(得分:1)

%Y将返回日历年份而不是ISO年份。要返回2017年的2017年1月1日的ISO年份,请改用%G。另请参阅Supported Format Elements for DATE

答案 1 :(得分:1)

以下是BigQuery Standard 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已经返回STRING