[英]Select the most recent value based on a given date
在Access中,我使用此虚拟表(table1),并希望使用下面显示的逻辑更新table2的字段。 例如,对于ID = 1,表2中field2的所有值应为10,而Date为<1/1/2015,并且该日期之后的所有值均应为8,依此类推。
Table1
ID field1 reviewDate
1 10 1/1/2014
1 8 1/1/2015
2 5 3/3/2013
2 6 4/4/2014
2 4 5/5/2015
Table2
ID field2 Date
1 10 1/1/2014
1 10 2/1/2014
. . .
. . .
1 8 1/1/2015
我首先尝试了一条select语句,以查看我离所需结果有多近,如下所示:
select a.ID, field1, max(reviewDate) as max , b.Date
from table1 a
inner join table2 b
on a.ID=b.ID
and b.Date >=a.reviewDate
group by ID,field1,reviewDate,Date
order by a.ID,b.Date
问题显然是,当Date大于相同ID的两个reviewDate时,将返回同一Date的两个值。 我只想要当代。 例如,对于仅在date = 2/1/2015 field2 = 8上的ID = 1,但是在我的Date = 2/1/2015脚本中,我有两个记录10和8。
我只是用一个相关的子查询来做到这一点:
select t2.*,
(select top 1 t1.field1
from table1 t1
where t1.id = t2.id and t1.reviewDate <= t2.Date
order by t1.reviewDate desc, t1.field1
) as field1
from table2 as t2;
我找到了一个解决方案,虽然可能不是最有效的,但仍然是一个解决方案。
我将ID,日期和相应的reviewDate存储在工作/临时表中。 使用此查询:
select a.ID,a.Date,max(ReviewDate) as RevDate
into temp1
from table1 a
inner join table2 b on a.ID=b.ID and a.Date>=b.ReviewDate
group by a.ID,a.Date
然后,我在table2中添加一个额外的列,ReviewDate列,更新加入temp1表的值
update table2 a
inner join temp1 b on a.ID=b.ID and a.date=b.date
set a.reviewDate=b.RevDate
然后在ID,date和reviewDate上更新加入table1的field2值。
update table2 a
inner join table1 b
on a.ID=b.ID and a.Date=b.Date and a.ReviewDate=b.Reviewdate
set a.field2=b.field1
我想可以合并一些步骤,但是我没有时间正确检查它。 请随意提供更有效的解决方案。 谢谢你们
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.