问题
I'm attempting to write an SQL statement to select a unique part number based on the most recent date. If I have just the two fields PartNo and ReceiveDate I could do:
"SELECT PartNo, Max(ReceiveDate) FROM Table GROUP BY PartNo;"
and this would return the unique PartNo and the most recent date.
The problem is that I also want to include the fields VendorName and Qty (But I just want PartNo to be unique). I've tried:
"SELECT PartNo, VendorName, Qty, Max(ReceiveDate) FROM Table GROUP BY PartNo;"
and
"SELECT PartNo, VendorName, Qty, Max(ReceiveDate) FROM Table GROUP BY PartNo, VendorName, Qty;"
I understand why these two SELECT statements are wrong, the first one doesn't run since VendorName and Qty aren't in the GROUP BY clause or part of an aggregate function, and in the second one it selects a unique record based on PartNo AND VendorName AND Qty, not just PartNo.
If someone could help me write the correct SQL statement that would be must appreciated. I'm using Microsoft Access which uses Jet SQL which is very similar to T-SQL.
回答1:
I would suggest a correlated subquery:
SELECT t.*
FROM Table as t
WHERE t.ReceiveDate = (SELECT MAX(t2.ReceiveDate)
FROM Table as t2
WHERE t2.PartNo = t.PartNo
);
In particular, this can take advantage of an index on (PartNo, ReceiveDate)
.
回答2:
If you mean, you don't care from which row Vendorname and Qty comes from (per partNo), then you can simply make them some aggregate function:
SELECT PartNo,
max(VendorName) as VendorName,
max(Qty) as Qty,
Max(ReceiveDate) as ReceiveDate
FROM [Table]
GROUP BY PartNo;
Probably a better approach would be to get those VendorName and Qty from the row with the last receive date (I assume that grouping return 1 date per PartNum):
select t.PartNo, t.VendorName, t.Qty, tmp.LastDate as ReceiveDate
from (SELECT PartNo, Max(ReceiveDate) as lastDate
FROM [Table]
GROUP BY PartNo) tmp
inner join [Table] t on t.PartNo = tmp.PartNo
where t.ReceiveDate = tmp.lastDate;
And I assume, no one really would name a table [Table].
回答3:
Try to use crosstab query:
SELECT DISTINCT X.PartNo,X.MaxDate,Y.VendorName,Y.Qty FROM
(SELECT PartNo, Max(ReceiveDate)MaxDate FROM Table GROUP BY PartNo)X,
(SELECT PartNo, VendorName, Qty From Table)Y
WHERE X.PartNo=Y.PartNo
来源:https://stackoverflow.com/questions/63487089/sql-selecting-multiple-fields-with-one-unique-field-based-on-most-recent-date