在BigQuery中将YYYYDDD字符串转换为YYYYMMDD

时间:2019-03-19 17:02:46

标签: sql google-bigquery

在SQL语句中是否可以将BigQuery的日期格式(如2007001)转换为等效的YYYYMMDD(2007-01-01)?

1 个答案:

答案 0 :(得分:1)

以下是用于BigQuery标准SQL

#standardSQL
SELECT date_in_yyyyddd,
  DATE_ADD(
    DATE(CAST(SUBSTR(date_in_yyyyddd, 1, 4) AS INT64),1,1), 
    INTERVAL CAST(SUBSTR(date_in_yyyyddd, 5, 3) AS INT64) - 1 DAY
  ) date_in_yyyymmdd

您可以使用下面的示例中的虚拟数据来测试,玩游戏

#standardSQL
WITH `project.dataset.table` AS (
  SELECT '2007001' date_in_yyyyddd UNION ALL
  SELECT '2007031' date_in_yyyyddd UNION ALL
  SELECT '2007061' date_in_yyyyddd 
)
SELECT date_in_yyyyddd,
  DATE_ADD(
    DATE(CAST(SUBSTR(date_in_yyyyddd, 1, 4) AS INT64),1,1), 
    INTERVAL CAST(SUBSTR(date_in_yyyyddd, 5, 3) AS INT64) - 1 DAY
  ) date_in_yyyymmdd
FROM `project.dataset.table`  

有结果

Row date_in_yyyyddd date_in_yyyymmdd     
1   2007001         2007-01-01   
2   2007031         2007-01-31   
3   2007061         2007-03-02    

上面产生的日期类型的字段的格式为yyyy-mm-dd 如果您需要yyyymmdd格式,则可以添加FORMAT_DATE,如下面的示例

SELECT date_in_yyyyddd,
  FORMAT_DATE('%Y%m%d', DATE_ADD(
    DATE(CAST(SUBSTR(date_in_yyyyddd, 1, 4) AS INT64),1,1), 
    INTERVAL CAST(SUBSTR(date_in_yyyyddd, 5, 3) AS INT64) - 1 DAY
  )) date_in_yyyymmdd   

所以相同的结果现在看起来像

Row date_in_yyyyddd date_in_yyyymmdd     
1   2007001         20070101     
2   2007031         20070131     
3   2007061         20070302