SQL Server -如何从另一个表中获取时间戳前后的2个值

jjjwad0x  于 2022-11-21  发布在  SQL Server
关注(0)|答案(2)|浏览(754)

我只是想知道有没有人能帮我解决这个问题。
我有两个表-表1和表2。
我试图做的是从表1中找到“日期”之前和之后的2个时间戳,因此表2中的所有内容都以粉红色突出显示。
如何在Microsoft SQL Server中完成此操作?理想情况下,不使用CTE。遗憾的是,Tableau不支持CTE。
先谢谢你了。

uyhoqukh

uyhoqukh1#

下面是一个使用CROSS JOIN、datediff()和row_number()的选项

Select Date
      ,Value
      ,ID
 From  (
        Select A.Date
              ,A.Value
              ,B.ID
              ,RN1 = row_number() over (order by datediff(second,a.date,b.date) desc) 
              ,RN2 = row_number() over (order by datediff(second,a.date,b.date) asc) 
         From Table2  A
         Cross Join Table1 B  
       ) A
 Where RN1 in (2,3)
   or  RN2 in (2,3)
 Order By Date

结果

q8l4jmvw

q8l4jmvw2#

如果 要 在 table2 中 选择 此 特定 范围 的 行 , 最 简单 的 方法 可能 是 union all

(
    select top (3) t2.date, t2.value
    from table1 t1
    inner join table2 t2 on t2.date < t1.date
    order by t2.date desc 
)
union all
(
    select top (3) t2.date, t2.value
    from table1 t1
    inner join table2 t2 on t2.date > t1.date
    order by t2.date
)

中 的 每 一 个
这 两 个 suquery 都 从 table1 中 的 引用 日期 开始 , 然后 使用 order byfetch 提取 table2 中 的 前 3 条 记录 ( 相应 地 , 后 3 条 记录 ) 。 这 两 个 数据 集 的 组合 将 给出 所 需 的 结果 。
如果 table1 非常 小 , 并且 在 table2(date) 上 有 相关 索引 , 那么 这 两 个 子 查询 的 执行 效率 应该 非常 高 。 将 列 value 添加 到 table2 索引 中 可能 会 进一步 提高 性能 , 因为 它 使 索引 * 覆盖 * 查询 。

相关问题