获取具有最大日期和空日期的ID的独特记录

时间:2017-05-26 01:51:55

标签: sql ms-access

这是我使用Left Join的表1和表2。 虽然看起来它可以在一张桌子里。 表1类似于主列表,其中id不能重复 所以在表2中我添加了id可以重复的名称和日期

+----+---------+----------------+
| id | Date    | Name           |
+----+---------+----------------+
| 1  | 5/25/17 | Monica Coleman |
| 1  | 5/26/17 | Kelsi Mines    |
| 2  |         |                |
| 3  | 5/9/17  | Vanessa Heart  |
| 4  | 5/8/17  | Ryan Evans     |
| 4  | 5/10/17 | Sharpay Evans  |
| 5  |         |                |
| 6  |         |                |
| 7  | 5/6/17  | Troy Bolton    |
+----+---------+----------------+

如果我使用此代码......

SELECT P.id, R.DateAdded, R.Name FROM Table1 AS P LEFT JOIN Table2 AS R ON P.id=R.id WHERE ((([R.DateAdded])=(SELECT MAX(DateAdded) FROM R WHERE InventoryID = R.InventoryID)));

......然后这些结果显示......

+----+---------+----------------+
| id | Date    | Name           |
+----+---------+----------------+
| 1  | 5/26/17 | Kelsi Mines    |
| 3  | 5/9/17  | Vanessa Heart  |
| 4  | 5/10/17 | Sharpay Evans  |
| 7  | 5/6/17  | Troy Bolton    |
+----+---------+----------------+

但是我想要的声明是......

+----+---------+----------------+
| id | Date    | Name           |
+----+---------+----------------+
| 1  | 5/26/17 | Kelsi Mines    |
| 2  |         |                |
| 3  | 5/9/17  | Vanessa Heart  |
| 4  | 5/10/17 | Sharpay Evans  |
| 5  |         |                |
| 6  |         |                |
| 7  | 5/6/17  | Troy Bolton    |
+----+---------+----------------+

2 个答案:

答案 0 :(得分:0)

在大多数数据库中,您可以将条件添加到ON子句(或使用ROW_NUMBER()。MS Access也不支持。因此,请使用子查询:

SELECT P.id, R.DateAdded, R.Name
FROM Table1 AS P LEFT JOIN
     (SELECT R.*
      FROM Table2 AS R
      WHERE R.DateAdded = (SELECT MAX(R2.DateAdded) FROM Table2 R2 WHERE R.InventoryID = R2.InventoryID)
     ) as R
     ON P.id = R.id

答案 1 :(得分:0)

好的,我得到了答案。我使用Is Null

SELECT P.id, R.DateAdded, R.Name FROM Table1 AS P LEFT JOIN Table2 AS R ON P.id=R.id WHERE ((([R.DateAdded])=(SELECT MAX(DateAdded) FROM R WHERE InventoryID = R.InventoryID))) OR R.DateAdded IS NULL;