我的表中已经有两列以时间戳格式显示骑自行车数据的开始和结束(这些列被称为started_at和ended_at)。我正在尝试创建另一个列,它显示了每一次骑行之间的差异,作为骑行长度。
我成功地添加了一个ride_length列,但无法找到每个差异,然后将其输入到该列中。我一直在测试很多方案,例如:
从TIMESTAMP_DIFF(ended_at,started_at,second)中选择length_test作为length_test
问题是,在所有计算中,输出几乎总是错误的。有时第一行是正确的,但其他行则不正确。我对SQL查询还不太了解,所以希望能提供帮助。
发布于 2022-06-09 20:30:12
如果您已经有了一个包含2列开始时间和结束时间的表,那么它实际上非常简单,正如您在time函数中已经提到的那样。
以下是向您展示的示例:
with source_table as (
select timestamp_sub(current_timestamp(), INTERVAL cast(RAND()*200 as int64) DAY) as start_timestamp, timestamp_sub(current_timestamp(), INTERVAL cast(RAND()*10 as int64) DAY) as end_timestamp
union all
select timestamp_sub(current_timestamp(), INTERVAL cast(RAND()*200 as int64) DAY) as start_timestamp, timestamp_sub(current_timestamp(), INTERVAL cast(RAND()*10 as int64) DAY) as end_timestamp
union all
select timestamp_sub(current_timestamp(), INTERVAL cast(RAND()*200 as int64) DAY) as start_timestamp, timestamp_sub(current_timestamp(), INTERVAL cast(RAND()*10 as int64) DAY) as end_timestamp
)
select start_timestamp, end_timestamp, timestamp_diff(end_timestamp,start_timestamp, SECOND) as time_difference_in_seconds from source_table示例输出如下所示:

如果希望将第三个值作为新列添加到源表中,那么只需覆盖源表的"all“,添加"timestamp_diff(end_timestamp,start_timestamp,SECOND)为time_difference_in_seconds”作为另一列。
https://stackoverflow.com/questions/72565430
复制相似问题