如何获取不大于记录日期的最新日期?

6pp0gazn  于 2021-08-01  发布在  Java
关注(0)|答案(2)|浏览(352)

我有一张表,上面有几个月的历史记录。我需要加入另一个表,该表包含有关对名称执行的“测试”的信息:

结果表应显示执行测试的最新id和日期,但测试日期不能大于数据月份:

你知道怎么做吗?

3df52oht

3df52oht1#

我猜你想要最新的 EOMONTH 从第二个表中选择第一个表中的每一行。如果这是正确的解释,那么您可以简单地使用 apply :

  1. select t1.*, t2.*
  2. from table1 t1 outer apply
  3. (select top (1) t2.*
  4. from table2 t2
  5. where t2.test_id = t1.test_id and t2.eomonth <= t1.test_date
  6. order by t2.eomonth desc
  7. ) t2;
xmakbtuz

xmakbtuz2#

这种连接非常有效:

  1. from table1 a
  2. left join table2 b on a.name = b.name and a.eomonth >= b.id_date and a.eomonth < LAG(b.id_date,1,'3000-01-01') OVER (PARTITION BY name ORDER BY b.id_date desc)

相关问题