Firstly, why are you using Truck002
's name
field rather than its id
field as the link to DispacthTable
? This is considered a less efficient way of doing it than using id
(which is either a numerical field or a shorter string than name
).
Secondly, you should mention in your Question that each Order
can have many DispatchTable
's and that each DispacthTable
can have many Truck002
's, otherwise many people will start by assuming that it is the other way round between DispatchTable
and Truck002
.
Thirdly, please try...
SELECT DispatchTable.ordernumber,
DispatchTable.truck,
DispatchTable.driver,
DispatchTable.actualpickup,
DispatchTable.actualdropoff,
orders.pickupdateandtime,
orders.dropoffdateandtime,
Truck002.lastposition,
Truck002.lastdateandtime
FROM DispatchTable
INNER JOIN orders ON DispatchTable.ordernumber = orders.id
INNER JOIN Truck002 ON DispatchTable.truck = Truck002.name
WHERE (orders.status = 'onRoute')
GROUP BY ordernumber
HAVING lastdateandtime = MAX( lastdateandtime )
If you have any questions or comments, then please feel free to post a Comment accordingly.
Further Reading
https://msdn.microsoft.com/en-us/library/bb177906(v=office.12).aspx (on HAVING
)
https://www.w3schools.com/sql/sql_having.asp (on HAVING
)
https://msdn.microsoft.com/en-us/library/bb177905(v=office.12).aspx (on GROUP BY
)
https://www.w3schools.com/sql/sql_groupby.asp (on GROUP BY
)