将TIME添加到DATETIME值

时间:2018-03-05 18:17:57

标签: google-bigquery

我可以从文档中看到DATETIME_ADD仅适用于INT64值,而不适用于TIME个对象。

我有DATETIME代表起点,然后是TIME对象中的持续时间

WITH input AS (
  SELECT
    DATE(2018,03,05) AS start_date,
    TIME(5,0,0) AS start_time,
    TIME(8,0,0) AS duration
)

SELECT
  *,
  DATETIME(start_date,start_time) AS start_datetime,
  DATETIME_ADD(
      DATETIME_ADD(
        DATETIME_ADD(
          DATETIME(start_date,start_time), 
          INTERVAL EXTRACT(HOUR FROM duration) HOUR
        ),
        INTERVAL EXTRACT(MINUTE FROM duration) MINUTE
      ),
        INTERVAL EXTRACT(SECOND FROM duration) SECOND
    ) AS end_datetime

FROM input

有一种更好的方法可以将TIME对象的3个值(小时,分钟,秒)添加到给定的DATETIME对象中吗?

1 个答案:

答案 0 :(得分:3)

以下是BigQuery Standard SQL

  
WITH input AS (
  SELECT
    DATE(2018,03,05) AS start_date,
    TIME(5,0,0) AS start_time,
    TIME(8,0,0) AS duration
)
SELECT
  *,
  DATETIME(start_date,start_time) AS start_datetime,
  DATETIME_ADD(
      DATETIME_ADD(
        DATETIME_ADD(
          DATETIME(start_date,start_time), 
          INTERVAL EXTRACT(HOUR FROM duration) HOUR
        ),
        INTERVAL EXTRACT(MINUTE FROM duration) MINUTE
      ),
        INTERVAL EXTRACT(SECOND FROM duration) SECOND
    ) AS end_datetime,
    DATETIME_ADD(
      DATETIME(start_date,start_time), 
      INTERVAL DATETIME_DIFF(DATETIME(start_date,duration), DATETIME(start_date), SECOND) SECOND
    ) end_datetime_nicer_way
FROM input