SQL查询以获取表中所有不同项的最新记录

时间:2010-05-06 03:41:08

标签: mysql distinct greatest-n-per-group

我有一张定义如下的所有销售表:

mysql> describe saledata;
+-------------------+---------------------+------+-----+---------+-------+
| Field             | Type                | Null | Key | Default | Extra |
+-------------------+---------------------+------+-----+---------+-------+
| SaleDate          | datetime            | NO   |     | NULL    |       | 
| StoreID           | bigint(20) unsigned | NO   |     | NULL    |       | 
| Quantity          | int(10) unsigned    | NO   |     | NULL    |       | 
| Price             | decimal(19,4)       | NO   |     | NULL    |       | 
| ItemID            | bigint(20) unsigned | NO   |     | NULL    |       | 
+-------------------+---------------------+------+-----+---------+-------+

我需要获得所有商品的最后售价(因为价格可能会发生变化)。我知道我可以运行如下查询:

SELECT price FROM saledata WHERE itemID = 1234 AND storeID = 111 ORDER BY saledate DESC LIMIT 1

但是,我希望能够获得所有项目的最后销售价格(ItemID存储在单独的项目表中)并将它们插入单独的表格中。我怎样才能获得这些数据?我尝试过这样的查询:

SELECT storeID, itemID, price FROM saledata WHERE itemID IN (SELECT itemID from itemmap) ORDER BY saledate DESC LIMIT 1

然后将其包装到插入中,但它没有获得正确的数据。是否有一个查询我可以运行以获取每个项目的最后价格并将其插入到定义为:

的表中
mysql> describe lastsale;
+-------------------+---------------------+------+-----+---------+-------+
| Field             | Type                | Null | Key | Default | Extra |
+-------------------+---------------------+------+-----+---------+-------+
| StoreID           | bigint(20) unsigned | NO   |     | NULL    |       | 
| Price             | decimal(19,4)       | NO   |     | NULL    |       | 
| ItemID            | bigint(20) unsigned | NO   |     | NULL    |       | 
+-------------------+---------------------+------+-----+---------+-------+

1 个答案:

答案 0 :(得分:4)

这是Stack Overflow上频繁出现的最大n组问题。

INSERT INTO lastsale (StoreID, Price, ItemID)
  SELECT s1.StoreID, s1.Price, s1.ItemID
  FROM saledata s1
  LEFT OUTER JOIN saledata s2
    ON (s1.Itemid = s2.Itemid AND s1.SaleDate < s2.SaleDate)
  WHERE s2.ItemID IS NULL;