![](/img/trans.png)
[英]SQL: Selecting multiple fields with one unique field based on most recent date
[英]SQL: Selecting record where values in one field are unique based off of most recent date
我正在尝试将 SQL 语句写入 select 条记录,以便每条记录都有一个唯一的 PartNo,并且我希望该记录基于最近的 ReceiveDate。 当我问这个问题时,我得到了答案:
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)
)
)
手动设置标准聚合查询(功能区中的 sigma 图标),其中按零件号分组且日期字段设置为 MAX...
运行查询以查看它是否返回您寻找的值...然后在设计视图中 - - select SQL 视图,这将为您提供 sql 语句...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.