首页 > 解决方案 > 从同一行中选择具有相关价格列的最新日期时间列

问题描述

我的数据库中有一张表,它正在跟踪一些价格。这些列是:id, product, factory, seller, platform,priceinserted

每天每 6 小时都会有新的记录与当前价格一起存储。例子:

1, Product 1, Factory 1, Seller 1, Platform 1, 99.99, 2019-08-07 02:12:35
2, Product 1, Factory 1, Seller 1, Platform 1, 95.99, 2019-08-06 20:12:35

现在我尝试选择带有价格的最新条目。一个条目应该是唯一的product, factory, seller, platform。所以我的sql查询现在是:

SELECT * 
  FROM prices 
 GROUP 
    BY product
     , factory
     , seller
     , platform
 ORDER 
    BY inserted DESC
     , price ASC

但是我现在如何获取每个条目的最新价格?一种解决方案是选择MAX(`inserted`),但如何从MAX(`inserted`)行中获取价格?

标签: mysqlselectgroup-by

解决方案


select p1.* from 
prices p1
join
(
  SELECT `product`, `factory`, `seller`, `platform`, max(inserted) as max_inserted
  FROM `prices` 
  GROUP BY `product`, `factory`, `seller`, `platform` 
) p2 on p1.product = p2.product
    and p1.factory = p2.factory
    and p1.seller = p2.seller
    and p1.platform = p2.platform
    and p1.inserted = p2.max_inserted

内部选择获取每个组的最新日期。然后加入反对以仅获取包含价格的相关记录。


推荐阅读