How to join to closest available date in Access? (1 Viewer)

higgs_89

New member
Local time
Today, 00:31
Joined
Sep 12, 2023
Messages
1
So I have the Following 2 tables in an access database

The first one that has information from when do we received emails and looks like this:

fromreceived
12 513/16/2023 2:49:56 PM
12 513/16/2023 2:51:17 PM
12 513/16/2023 2:51:57 PM
12 513/16/2023 3:10:48 PM
12 513/17/2023 3:23:01 PM
12 513/17/2023 5:33:18 PM
12 513/20/2023 6:23:31 PM

And the second table that has data from when we answer and looks like this:

to from
12 513/17/2023 10:00:32 AM
12 513/17/2023 3:35:15 PM
12 513/20/2023 10:40:01 AM
12 513/21/2023 8:47:02 AM

What I want to do is to have them both joined to catch the next closest date that we answer the email, I have tried this

Code:
SELECT
    RE.[From] AS ReceivedFrom,
    SE.[To] AS SentTo,
    SE.[Sent] AS SentDate,
    RE.[Received] AS ReceivedDate
FROM
    [Client Recieved Filtered data] AS RE
LEFT JOIN
    (
        SELECT DISTINCT
            SE1.[To],
            SE1.[Sent],
            RE1.[From],
            RE1.[Received],
            (
                SELECT TOP 1
                    ABS(DateDiff("s", SE2.[Sent], RE1.[Received]))
                FROM
                    [sent email filtered data] AS SE2
                WHERE
                    SE2.[To] = RE1.[From]
                ORDER BY
                    ABS(DateDiff("s", SE2.[Sent], RE1.[Received]))
            ) AS MinTimeDiff
        FROM
            [sent email filtered data] AS SE1
        INNER JOIN
            [Client Recieved Filtered data] AS RE1
        ON
            SE1.[To] = RE1.[From]
    ) AS SE
ON
    RE.[From] = SE.[From]
    AND ABS(DateDiff("s", SE.[Sent], RE.[Received])) = SE.MinTimeDiff;

But it's not giving me the next date that the email was answered, can anybody help me with this?
 

ebs17

Well-known member
Local time
Today, 08:31
Joined
Feb 7, 2020
Messages
1,946
SQL:
SELECT
   RE.[From] AS ReceivedFrom,
   RE.[Received] AS ReceivedDate,
   MIN(SE.[Sent]) AS SentDate
FROM
   [Client Recieved Filtered data] AS RE
      LEFT JOIN [sent email filtered data] AS SE
      ON RE.[From] = SE.[To]
         AND
      RE.[Received] <= SE.[Sent]
GROUP BY
   RE.[From],
   RE.[Received]
 
Last edited:

Users who are viewing this thread

Top Bottom