问题
I have a table:
ItemID PurchaseDate Price
001 03/17/2013 19.00
002 03/17/2013 14.00
001 03/18/2013 13.00
002 03/18/2013 15.00
001 03/19/2013 17.00
003 03/19/2013 19.00
I need to write a SQL query
to get the Price
corresponding to the latest PurchaseDate
for each ItemID
.
Entries in table might not necessarily be entered ordered by date
Like this:
ItemID PurchaseDate Price
001 03/19/2013 17.00
002 03/18/2013 15.00
003 03/19/2013 19.00
回答1:
The idea behind the subquery is it separately gets the latest PurchaseDate
for each ItemID
. The result of the subquery is then joined back on the table provided that it matches on two conditions: ItemID
and PurchaseDate
.
SELECT a.*
FROM TableName a
INNER JOIN
(
SELECT ItemID, MAX(PurchaseDate) max_date
FROM TableName
GROUP BY ItemID
) b ON a.ItemID = b.ItemID AND
a.PurchaseDate = b.max_date
回答2:
-- WITH clause, works with Oracle.
-- I added this clause to dynamically run the SELECT statement without any DDL.
-- Ignore this section for use on MS Access
WITH v AS (
SELECT 001 ItemID, TO_DATE('03/17/2013', 'MM/DD/YYYY') PurchaseDate, 19.00 Price FROM dual
UNION ALL
SELECT 002, TO_DATE('03/17/2013', 'MM/DD/YYYY'), 14.00 FROM dual
UNION ALL
SELECT 001, TO_DATE('03/18/2013', 'MM/DD/YYYY'), 13.00 FROM dual
UNION ALL
SELECT 002, TO_DATE('03/18/2013', 'MM/DD/YYYY'), 15.00 FROM dual
UNION ALL
SELECT 001, TO_DATE('03/19/2013', 'MM/DD/YYYY'), 17.00 FROM dual
UNION ALL
SELECT 003, TO_DATE('03/19/2013', 'MM/DD/YYYY'), 19.00 FROM dual
)
-- The WITH clause was upto here.
-- Below starts the main query which works on most platforms including MS Access.
-- I have referenced to the same table "v" two times - v_in and v_out.
-- You will need to change the "v" with your table name.
SELECT v_out.itemid, v_out.purchasedate, v_out.price
FROM v v_out
WHERE EXISTS (SELECT 1
FROM v v_in
WHERE v_in.itemid = v_out.itemid
GROUP BY v_in.itemid
HAVING MAX(v_in.purchasedate) = v_out.purchasedate)
ORDER BY v_out.itemid
;
来源:https://stackoverflow.com/questions/15495133/get-most-recent-price-for-each-item