1

我有一张桌子:

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每个. 表中的条目可能不一定按日期顺序输入,如下所示: PurchaseDateItemID

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

2 回答 2

7

子查询背后的想法是它分别获取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
于 2013-03-19T09:03:25.167 回答
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
;
于 2013-03-19T09:11:04.950 回答