如何将MILLISECOND与date_add和date_diff一起使用

时间:2019-03-18 10:43:14

标签: google-bigquery

在bigquery中尝试将MILLISECOND与date_add函数一起使用时,我有些卡住:

我正在尝试对我不起作用的SQL

DATE_ADD(MILLISECOND,-1,LEAD(dt) OVER (PARTITION BY xy ORDER BY dt ASC)

还在寻找DATE_DIFF函数的解决方案

我们非常感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

这是使用DATETIME_ADD

的有效示例
SELECT *, DATETIME_DIFF(seq_date,LEAD_DT, HOUR) FROM  
(SELECT *, RANK() OVER (PARTITION BY ID ORDER BY seq_date) AS RNK,
DATETIME_ADD((LEAD(seq_date) OVER (PARTITION BY ID ORDER BY seq_date)) ,INTERVAL 3 HOUR) LEAD_DT
FROM 
(select 1 as id, CURRENT_DATETIME() as seq_date, 10 as cost
union ALL
select 1 as id, DATETIME_ADD(CURRENT_DATETIME(), INTERVAL -10 MINUTE ) as seq_date, 12 as cost
UNION ALL
select 1 as id, DATETIME_ADD(CURRENT_DATETIME(), INTERVAL -1 HOUR ) as seq_date, 13 as cost
UNION ALL
select 1 as id, DATETIME_ADD(CURRENT_DATETIME(), INTERVAL 5 HOUR ) as seq_date, 20 as cost));

这是使用DATE_ADD

的有效示例
SELECT *, DATE_DIFF(seq_date,LEAD_DT, DAY) FROM  
(SELECT *, RANK() OVER (PARTITION BY ID ORDER BY seq_date) AS RNK,
DATE_ADD((LEAD(seq_date) OVER (PARTITION BY ID ORDER BY seq_date)) ,INTERVAL 3 DAY) LEAD_DT
FROM 
(select 1 as id, CURRENT_DATE() as seq_date, 10 as cost
union ALL
select 1 as id, DATE_ADD(CURRENT_DATE(), INTERVAL -10 DAY ) as seq_date, 12 as cost
UNION ALL
select 1 as id, DATE_ADD(CURRENT_DATE(), INTERVAL -1 DAY ) as seq_date, 13 as cost
UNION ALL
select 1 as id, DATE_ADD(CURRENT_DATE(), INTERVAL 5 DAY ) as seq_date, 20 as cost));

您可以在link下面进行详细了解

答案 1 :(得分:1)

DATE_ADD需要date_part作为参数。您可以为此使用DATATIME_ADD。这对我有用:

db.Select

播放一些虚拟数据:

DATETIME_ADD(LEAD(validfrom) OVER (PARTITION BY xy ORDER BY validfrom ASC), INTERVAL -1 MILLISECOND) as validto

这是结果:

WITH test_table as
(
    SELECT 1 AS xy, CURRENT_DATETIME() AS validfrom UNION ALL
    SELECT 1 AS xy, DATETIME_ADD(CURRENT_DATETIME(), INTERVAL 1 MINUTE ) AS validfrom UNION ALL
    SELECT 1 AS xy, DATETIME_ADD(CURRENT_DATETIME(), INTERVAL 2 MINUTE ) AS validfrom UNION ALL
    SELECT 1 AS xy, DATETIME_ADD(CURRENT_DATETIME(), INTERVAL 3 MINUTE ) AS validfrom
)
SELECT
  *,
  DATETIME_ADD(LEAD(validfrom) OVER (PARTITION BY xy ORDER BY validfrom ASC), INTERVAL -1 MILLISECOND) as validto
FROM test_table;

请注意,Row xy validfrom validto 1 1 2019-03-18T15:06:18.086840 2019-03-18T15:07:18.085840 2 1 2019-03-18T15:07:18.086840 2019-03-18T15:08:18.085840 3 1 2019-03-18T15:08:18.086840 2019-03-18T15:09:18.085840 4 1 2019-03-18T15:09:18.086840 null 字段比下一行的validto早1毫秒,应该是预期的结果。