访问查询以在最近的时间加入两个表

时间:2017-02-08 00:43:46

标签: sql ms-access

我有两个访问表,我需要根据公共列(dest)和表B中最接近表A的时间进行连接。

航班(表A)

ID | dest | land
1  | SUN  | 1/1/2017 8:52:00 AM
2  | SEA  | 1/1/2017 4:39:00 AM

天气(表B)

ID | dest | time                | vis 
1  | SUN  | 1/1/2017 8:15:00 AM | 10
2  | SUN  | 1/1/2017 8:35:00 AM | 5
3  | SUN  | 1/1/2017 8:55:00 AM | 2
4  | SEA  | 1/1/2017 2:48:00 AM | 7
5  | SEA  | 1/1/2017 3:52:00 AM | 10
6  | SEA  | 1/1/2017 4:49:00 AM | 2

期望的结果(表C)

ID | dest | land                | time                | vis
1  | SUN  | 1/1/2017 8:52:00 AM | 1/1/2017 8:35:00 AM | 5
2  | SEA  | 1/1/2017 4:39:00 AM | 1/1/2017 3:52:00 AM | 10

我一直坚持如何加入'dest'和最接近的时间。表A包含~25,000行,表B~100,000。

1 个答案:

答案 0 :(得分:1)

我会这样做:

SELECT Flights.dest, Flights.land, 
(select time from weather 
    where id = (select top 1 id 
                from weather 
                where dest=flights.dest and time <= flights.land 
                order by time desc)) AS [time], 
(select vis from weather 
    where id = (select top 1 id 
                from weather 
                where dest=flights.dest and time <= flights.land 
                order by time desc)) AS vis
FROM Flights;

或者,使用此查询可以获得相同的结果:

SELECT Flights.dest, Flights.land, 
weather.time, weather.vis
FROM Flights INNER JOIN weather ON Flights.dest = weather.dest
WHERE weather.time = (
   select top 1 time 
   from weather 
   where dest=flights.dest and time <= flights.land 
   order by time desc);