sql - 如何将带有时间戳的表加入状态更改表
问题描述
我已经看到了如何加入最近的时间戳的答案,但我对如何用 sql 做简单的逻辑感到困惑。
我有 2 个表,表 1 带有 [timestamp],表 2 带有 [timestamp, status_change]。
我如何获得带有 [timestamp, status] 的表格?
我可以通过从表 2 中获取每个状态的开始和结束时间列表来使用程序执行此操作,然后为表 1 中的每个时间戳循环遍历列表并分配一个状态。
与此等效的 sql 是什么?
解决方案
如果我理解正确,您需要来自 的时间戳t1
和来自 的状态t2
。相关子查询(或横向连接)执行此操作:
select t1.*,
(select top (1) t2.status
from t t2
where t2.timestamp <= t1.timestamp
order by t2.timestamp desc
) as status
from t1;
另一种方法使用lead()
with left join
:
select t1.*, t2.status
from t1 left join
(select t2.*,
lead(timestamp) over (order by timestamp) as next_timestamp
from t2
) t2
on t1.timestamp >= t2.timestamp and
(t1.timestamp < t2.next_timestamp or t2.next_timestamp is null);
推荐阅读
- reactjs - 如何将 typeface-open-sans 与 styled-components sheet.collectStyles 一起使用?
- javascript - 当对象被推入Angular中的数组时更新视图
- python-3.x - ValueError:matmul:输入操作数0没有足够的维度(有0,带有签名的gufunc核心(n?,k),(k,m?)->(n?,m?)需要1)
- javascript - 如果某列满足条件,我想运行删除行功能
- python - 更改在熊猫中矢量化的这一行和上一行
- python - 尽管版本控制正确,但无法从“tensorflow.python.keras.engine”导入名称“keras_tensor”
- eclipse - Gradle Daemon 似乎启动了多个 java exe
- git - 如何让 github 操作工作流使用机器人名称将生成的文档推送到同一组织中的其他存储库
- python - 打开串行端口连接问题 - 找不到端口路径(Windows)
- python - 什么可能导致我的程序在一个函数上运行两次,即使它应该在运行一次后退出?