I have a query that returns a datetime field and several other fields along with it. I want to add a field from another table that also has a datetime field. I cannot inner join these two tables since the datetime fields aren’t related, so instead want to join the first row in the second table that occurs just after the datetime field in the first table. Here’s a non-functional pseudo query of what I am trying to go for:
SELECT DISTINCT
TripID AS 'ID',
@CURRDATE = CurrDate,
@GROUPID = GroupID,
UserEmail AS 'User',
RouteID AS 'Route',
(SELECT TOP (1) PatternNum
FROM tblMOEHistory
WHERE (GroupID = @GROUPID)
AND (TimeStamp > @CURRDATE)
ORDER BY TimeStamp) AS 'Pattern'
FROM tblMobileTrips
ORDER BY 'Time';
I’m not sure if there is a way to do this but I was hoping someone might be able to help me out.
You can indeed use a join… give this a shot: