选择每个记录的最高值

时间:2018-06-21 21:33:20

标签: sql vba ms-access

一段时间以来,我一直在努力进行这种查询/查询设计,我认为是时候咨询专家了!这是我的表格结果:

ID   | Status       | date         |
---------------------------------
05   | Returned     | 20/6/2018    |
03   | Sent         | 12/5/2018    |
01   | Pending      | 07/6/2018    |
01   | Engaged      | 11/4/2018    |
03   | Contacted    | 16/4/2018    |
05   | Surveyed     | 04/3/2017    |
05   | No Contact   | 05/3/2017    |

如何获取每个ID的最高/最新值:

ID   | Status       | date         |
---------------------------------
05   | Returned     | 20/6/2018    |
03   | Sent         | 12/5/2018    |
01   | Pending      | 07/6/2018    |

我尝试了分组方式,TOP 1,不同,结果仍然不是我想要的。另外,由于ID可以超过3种类型,因此也不显示前5%的结果。

以下我的查询:

INSERT INTO TmpAllcomsEmployee ( StatusID, EmployeeID, CommunicationDate )
SELECT DISTINCT CommunicationLog.StatusID, TmpAllcomsEmployee.EmployeeID, 
Max(CommunicationLog.CommunicationDate) AS MaxOfCommunicationDate
FROM CommunicationLog RIGHT JOIN TmpAllcomsEmployee ON 
     CommunicationLog.EmployeeID = TmpAllcomsEmployee.EmployeeID
GROUP BY CommunicationLog.StatusID, TmpAllcomsEmployee.EmployeeID
ORDER BY Max(CommunicationLog.CommunicationDate) DESC;

1 个答案:

答案 0 :(得分:1)

一种方法是相关子查询:

select cl.*
from CommunicationLog as cl
where cl.date = (select max(cl2.date)
                 from CommunicationLog as cl2
                 where cl2.EmployeeID = cl.EmployeeID
                );

这将获取CommunicationLog中每位员工的最新记录。如果确实需要,可以加入另一个表。除非您将其用于过滤,否则似乎没有必要。