我有一张表:
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
我需要写一个,SQL query以获取Price与PurchaseDate每个最新的对应ItemID。表中的条目不一定按日期顺序输入,就像这样:
SQL query
Price
PurchaseDate
ItemID
ItemID PurchaseDate Price 001 03/19/2013 17.00 002 03/18/2013 15.00 003 03/19/2013 19.00
子查询背后的想法是,它分别PurchaseDate为每个子查询获取最新信息ItemID。然后将子查询的结果被接合回只要它对两个条件相匹配的表:ItemID和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