BigQuery日期和时间函数在时间戳列上返回NULL

时间:2015-09-09 06:51:59

标签: google-bigquery

我正在使用LAG()和LEAD()从表中的一个时间戳列中提取3个时间戳列:timestamp,prev_timestamp,next_timestamp。我需要做一些简单的日期&时间格式化,但当我在prev_timestamp或next_timestamp上使用像MONTH()这样的函数时,它返回NULL。

结果列的模式类型是正确的(TIMESTAMP),并且由于某种原因,常规时间戳日期和时间格式设置有效。如何使它为所有3列正确返回月份?

返回timestamp列的月份的示例代码,以及prev和next timestamp列的NULL:

SELECT 
  MONTH(timestamp) AS month,
  MONTH(prev_timestamp) AS prev_month,
  MONTH(next_timestamp) AS next_month
FROM (
  SELECT
    timestamp,
    LAG(timestamp,1) OVER (PARTITION BY id ORDER BY timestamp) prev_timestamp,
    LEAD(timestamp,1) OVER (PARTITION BY id ORDER BY timestamp) next_timestamp
  FROM timestamp_table
  )

2 个答案:

答案 0 :(得分:0)

尝试以下

SELECT 
  MONTH(MSEC_TO_TIMESTAMP(timestamp)) AS month,
  MONTH(MSEC_TO_TIMESTAMP(prev_timestamp)) AS prev_month,
  MONTH(MSEC_TO_TIMESTAMP(next_timestamp)) AS next_month
FROM (
  SELECT
    timestamp,
    LAG(timestamp,1) OVER (PARTITION BY id ORDER BY timestamp) prev_timestamp,
    LEAD(timestamp,1) OVER (PARTITION BY id ORDER BY timestamp) next_timestamp
  FROM timestamp_table
  )

答案 1 :(得分:0)

所以经过测试和检查了几件事后,我实际上从Mikhail's answer启发了自己,并意识到他的答案是不正确的,因为滞后/导致不返回毫秒,而是MICRO秒(为什么?这是任何人的猜测)

SELECT 
  MONTH(timestamp) AS month,
  MONTH(MSEC_TO_TIMESTAMP((prev_timestamp/1000))) AS prev_month,
  MONTH(MSEC_TO_TIMESTAMP((next_timestamp/1000))) AS next_month
FROM (
  SELECT
    timestamp,
    LAG(timestamp,1) OVER (PARTITION BY id ORDER BY timestamp) prev_timestamp,
    LEAD(timestamp,1) OVER (PARTITION BY id ORDER BY timestamp) next_timestamp
  FROM timestamp_table
  )

应该有效。我刚刚测试了创建一个包含三行时间戳的表。在没有/ 1000的情况下使用它,我的滞后/主导版本给出了不同的月份。我测试了结果,如果你不做分工,你最终会在47世纪的某个地方。