SQL从表中选择最大日期,只有1个日期

时间:2018-06-08 19:28:45

标签: sql ms-access ms-access-2007

我有这个SQL代码:

SELECT MH.[PM#], 
       MH.[Work Done], 
       MH.[Date Done], 
       MH.Comments, 
       MH.[SEM Completed by]
 FROM [Maintenance History tbl] AS MH
WHERE (((MH.[Work Done])="LT") 
  AND ((MH.[Date Done]) =
        ( SELECT Max(MH2.[Date Done])
            FROM [Maintenance History tbl] AS MH2
           WHERE MH2.[PM#] = MH.[PM#]
        )
      ));

这将选择完成日期最近的四个字段。

如果只有一行,这不起作用。

如果只有1行,如何让它返回最大日期?

1 个答案:

答案 0 :(得分:0)

我认为你错过了子查询中的过滤条件Work Done = "LT"。尝试添加它,如:

SELECT MH.[PM#], 
       MH.[Work Done], 
       MH.[Date Done], 
       MH.Comments, 
       MH.[SEM Completed by]
 FROM [Maintenance History tbl] AS MH
WHERE (MH.[Work Done] = "LT"
  AND (MH.[Date Done] =
        ( SELECT Max(MH2.[Date Done])
            FROM [Maintenance History tbl] AS MH2
           WHERE MH2.[PM#] = MH.[PM#]
             and MH2.[Work Done] = "LT"
        )
      ));