首页 > 解决方案 > 如何将带有时间戳的表加入状态更改表

问题描述

我已经看到了如何加入最近的时间戳的答案,但我对如何用 sql 做简单的逻辑感到困惑。

我有 2 个表,表 1 带有 [timestamp],表 2 带有 [timestamp, status_change]。

我如何获得带有 [timestamp, status] 的表格?

我可以通过从表 2 中获取每个状态的开始和结束时间列表来使用程序执行此操作,然后为表 1 中的每个时间戳循环遍历列表并分配一个状态。

与此等效的 sql 是什么?

标签: sqlsql-server

解决方案


如果我理解正确,您需要来自 的时间戳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);

推荐阅读