获取每件商品的最新价格

时间:2013-03-19 09:00:51

标签: sql ms-access greatest-n-per-group

我有一张桌子:

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。 表中的条目可能不一定按日期排序 像这样:

ItemID PurchaseDate Price  
001 03/19/2013 17.00  
002 03/18/2013 15.00  
003 03/19/2013 19.00  

2 个答案:

答案 0 :(得分:4)

子查询背后的想法是它为每个PurchaseDate单独获取最新的ItemID。然后,子查询的结果将重新连接到表中,前提是它匹配两个条件:ItemIDPurchaseDate

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

答案 1 :(得分:3)

-- 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
;