我有一张表,上面有几个月的历史记录。我需要加入另一个表,该表包含有关对名称执行的“测试”的信息:结果表应显示执行测试的最新id和日期,但测试日期不能大于数据月份:你知道怎么做吗?
3df52oht1#
我猜你想要最新的 EOMONTH 从第二个表中选择第一个表中的每一行。如果这是正确的解释,那么您可以简单地使用 apply :
EOMONTH
apply
select t1.*, t2.*from table1 t1 outer apply (select top (1) t2.* from table2 t2 where t2.test_id = t1.test_id and t2.eomonth <= t1.test_date order by t2.eomonth desc ) t2;
select t1.*, t2.*
from table1 t1 outer apply
(select top (1) t2.*
from table2 t2
where t2.test_id = t1.test_id and t2.eomonth <= t1.test_date
order by t2.eomonth desc
) t2;
xmakbtuz2#
这种连接非常有效:
from table1 aleft 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)
from table1 a
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)
2条答案
按热度按时间3df52oht1#
我猜你想要最新的
EOMONTH
从第二个表中选择第一个表中的每一行。如果这是正确的解释,那么您可以简单地使用apply
:xmakbtuz2#
这种连接非常有效: