仅显示访问查询中的最后一个重复项

时间:2013-11-21 17:33:27

标签: sql ms-access-2007 unique distinct duplicate-removal

我有一个访问数据库,我在那里记录我借出的地图。所以我有一个名为MapsOut的表,包括字段,MapNum(地图ID),MapName(地图名称),CheckOut(地图被借出的日期),CheckIn(返回地图的日期)。

MapNum MapName CheckOut CheckIn
1      London  01/02/13 07/05/13
1      London  08/05/13 16/06/13
1      London  19/07/13 
2      Hull    30/01/13 05/03/13
2      Hull    06/04/13 01/05/13
3      Derby   11/01/13 17/02/13
3      Derby   05/09/13 06/10/13
4      Hove    01/02/13 01/03/13

我想编写一个查询,只给我每个MapNum的最后一条记录,但只显示那些已经重新检入的记录,所以我知道哪个是最后一个,并且按照最近到最长时间的顺序,在CheckOut列中。所以结果应该是这样的:

MapNum MapName CheckOut CheckIn
4      Hove    01/02/13 01/03/13
2      Hull    06/04/13 01/05/13
3      Derby   05/09/13 06/10/13

我已经进行了查询,但是我无法使用Select DISTINCT,因为它仍然显示重复。

这是不起作用的:

SELECT DISTINCT Maps.MapNum AS MapNum, Maps.MapName, Max(MapsOut1.CheckOut) AS CheckOut, MapRecords.CheckIn
FROM (MapRecords INNER JOIN Maps ON MapRecords.MapNum = Maps.MapNum) INNER JOIN (MapsOut INNER JOIN MapsOut1 ON MapsOut.ID = MapsOut1.ID) ON Maps.MapNum = MapsOut.MapNum
GROUP BY Maps.MapNum, Maps.MapName, MapRecords.CheckIn
HAVING (((MapRecords.CheckIn) Is Not Null))
ORDER BY Maps.MapNum;

非常感谢任何帮助。

提前致谢

2 个答案:

答案 0 :(得分:1)

从查询开始查找每个[MapNum]的最新条目

SELECT MapNum, Max(CheckOut) AS MaxOfCheckOut
FROM MapData
GROUP BY MapNum

返回

MapNum  MaxOfCheckOut
------  -------------
     1  2013-07-19   
     2  2013-04-06   
     3  2013-09-05   
     4  2013-02-01   

我们可以使用它作为子查询来返回每个行的其余字段,但仅当[CheckIn]不是Null

SELECT md.MapNum, md.MapName, md.CheckOut, md.CheckIn
FROM
    MapData md
    INNER JOIN
    (
        SELECT MapNum, Max(CheckOut) AS MaxOfCheckOut
        FROM MapData
        GROUP BY MapNum
    ) AS mx
        ON md.MapNum = mx.MapNum 
            AND md.CheckOut = mx.MaxOfCheckOut
WHERE md.CheckIn IS NOT NULL
ORDER BY md.CheckOut DESC

返回

MapNum  MapName  CheckOut    CheckIn   
------  -------  ----------  ----------
     3  Derby    2013-09-05  2013-10-06
     2  Hull     2013-04-06  2013-05-01
     4  Hove     2013-02-01  2013-03-01

答案 1 :(得分:0)

尝试这样的事情:

SELECT m.MapNum AS MapNum,
  m.MapName AS MapName,
  mr.CheckOut AS CheckOut,
  mr.CheckIn AS CheckIn
FROM maps m
INNER JOIN (
  SELECT t1.*
  FROM MapsRecords t1
  LEFT JOIN MapsRecords t2 ON t1.MapNum = t2.MapNum
    AND t1.checkOut < t2.checkOut
  WHERE t2.checkOut IS NULL
    AND t1.CheckIn IS NOT NULL
  ) mr ON m.MapNum = mr.MapNum;

这应该可以满足您的需求。 内部查询获取具有最新结帐日期的记录,即他的签入不为空。其余的只是与地图的连接。

sqlfiddle demo in sql-server

注意:这个演示是在sql-server中,但我认为没有理由在访问中不起作用。