SQL:根据最近的日期选择一个字段中的值唯一的记录

标签 sql tsql ms-access

我正在尝试编写一条 SQL 语句来选择记录,以便每条记录都有一个唯一的 PartNo,并且我希望该记录基于最近的 ReceiveDate。当我问 this 时,我得到了答案问题:

SELECT t.*
FROM Table as t
WHERE t.ReceiveDate = (SELECT MAX(t2.ReceiveDate)
                       FROM Table as t2
                       WHERE t2.PartNo = t.PartNo
                      );

但是,此答案假设对于每个 ReceiveDate,您不会有两次相同的 PartNo。在有多个相同PartNo和ReceiveDate的记录的情况下,选择哪个并不重要,但我只想选择一个(PartNo必须是唯一的)

例子:

PartNo | Vendor | Qty | ReceiveDate
 100   |  Bob   | 2   | 2020/07/30
 100   | Bob    | 3   | 2020/07/30

应该只返回其中一条记录。

我正在使用 Microsoft Access,它使用与 T-SQL 非常相似的 Jet SQL。

最佳答案

使用NOT EXISTS:

select distinct t.*
from tablename as t
where not exists (
  select 1 from tablename
  where partno = t.partno
  and (
    receivedate > t.receivedate
    or (receivedate = t.receivedate and qty > t.qty)
    or (receivedate = t.receivedate and qty = t.qty and vendor > t.vendor)
  )
)

关于SQL:根据最近的日期选择一个字段中的值唯一的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63490646/

相关文章:

sql - MySQL LEFT JOIN SELECT 不选择所有左侧记录?

sql - 表字段命名约定和 SQL 语句

SQL 左外连接不提供完整表

sql-server - 如何通过累积连接获取 SQL 中字符串值的分组

sql-server - 通过检查现有数据启用外键

mysql - MYSQL中如何使用MS Access 2010附加文件

php - 使用数组元素运行 sql 查询

sql - Group By 子句导致错误

java - JDBC ODBC 驱动程序连接

date - MS Access 2010(设计 View ): return Monday of the current week with Monday as 1st day of the week