我正在尝试编写一条 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/