msaccess将最近的匹配记录从一个表加入另一个表

时间:2015-08-01 19:42:25

标签: ms-access join ms-access-2010 left-join

我想要的结果。

+--------+-------------+------------+--------+
|  Tag   | most_recent |  Comment   | Author |
+--------+-------------+------------+--------+
| TAG001 | 2015-07-23  | Something3 | AM     |
| TAG002 | 2015-07-25  | Something5 | BN     |
+--------+-------------+------------+--------+

我的表格:

状态

+--------+-------------+------------+
|  Tag   |   Status    | DateStatus |
+--------+-------------+------------+
| TAG001 | Not Started |            |
| TAG002 | Complete    | 2015-07-23 |
+--------+-------------+------------+

评论

+----+--------+-------------+------------+--------+
| ID |  Tag   | DateCreated |  Comment   | Author |
+----+--------+-------------+------------+--------+
|  1 | TAG001 | 2015-07-22  | Something1 | JS     |
|  2 | TAG002 | 2015-07-23  | Something2 | JS     |
|  3 | TAG001 | 2015-07-23  | Something3 | AM     |
|  4 | TAG002 | 2015-07-23  | Something4 | AS     |
|  5 | TAG002 | 2015-07-25  | Something5 | BN     |
+----+--------+-------------+------------+--------+

我尝试了4个不同的查询,每个查询都变得越来越复杂,但仍无效。

我尝试过的查询:

查询1)

SELECT Comments.[Tag], Max(Comments.[DateCreated]) AS most\_recent
FROM Comments
GROUP BY Comments.[Tag];

结果1)

+--------+-------------+
|  Tag   | most_recent |
+--------+-------------+
| TAG001 | 2015-07-23  |
| TAG002 | 2015-07-25  |
+--------+-------------+

只是给我最近的日期,但没有价值。

查询2)

SELECT Comments.[Tag], Max(Comments.[DateCreated]) AS most\_recent
FROM Comments
GROUP BY Comments.[Tag];

结果2)

+--------+-------------+------------+
|  Tag   | most_recent |  Comment   |
+--------+-------------+------------+
| TAG001 | 2015-07-22  | Something1 |
| TAG001 | 2015-07-23  | Something3 |
| TAG002 | 2015-07-23  | Something2 |
| TAG002 | 2015-07-23  | Something4 |
| TAG002 | 2015-07-25  | Something5 |
+--------+-------------+------------+

现在我看到了我想要的所有信息,但我无法过滤最近的信息。

我尝试了DISTINCT,但它没有用。

查询3)

从此处修改:MYSQL - Join most recent matching record from one table to another

SELECT Status.\*,Comments.\*
FROM Status S
LEFT JOIN Comments C ON S.tag = C.tag
JOIN(SELECT x.tag, MAX(x.DateCreated) AS MaxCommentDate FROM Comments x
GROUP BY x.tag) y ON y.tag = x.tag AND y.MaxCommentDate = x.DateCreated

结果:查询表达式中的语法错误(缺少运算符)

查询4)

从这里修改: Left Join to most recent record

SELECT
Status.\*,Comments.\*
FROM Status S
LEFT JOIN
(
Comments C
INNER JOIN
(
SELECT
x.tag, MAX(x.DateCreated) AS MaxCommentDate
FROM
Comments x
GROUP BY
x.tag
)
y
ON y.tag = x.tag
AND y.MaxCommentDate = x.DateCreated
)
ON S.tag = C.tag;

结果:JOIN上的语法错误

没有太多运气......感谢先进。

感谢。

1 个答案:

答案 0 :(得分:1)

以下内容在Access 2010中似乎对我有用:

SELECT c.Tag, c.DateCreated AS most_recent, c.Comment, c.Author
FROM
    (
        SELECT Tag, MAX(DateCreated) AS MaxDate 
        FROM Comments 
        GROUP BY Tag
    ) AS md
    INNER JOIN
    Comments AS c
        ON c.Tag = md.Tag AND c.DateCreated = md.MaxDate