如何使用mySQL选择具有一列最大值的结果,按另一列分组?

时间:2013-12-24 16:50:30

标签: mysql select

不确定问题有多大意义,但希望我能用一个例子来解释。

我有一个包含以下列的表:

PriceHistoryID, PriceChangeDate, DealID, Price

这些是主键,日期,外键和价格。设置此项时,每次为“交易”更改价格时,都会在此表格中创建新行。

我想要做的是创建一个SELECT,其中为每个唯一的DealID返回1行,而该行是PriceChangeDate最新的行。

我觉得我以前做过这样的事情,看起来并不困难,但我画的是空白。谢谢你的帮助!

2 个答案:

答案 0 :(得分:2)

在MySQL中,您可以使用子查询并加入:

select d.*
from deals d join
     (select DealId, max(PriceChangeDate) as maxPriceChangeDate
      from deals
      group by DealId
     ) dmax
     on d.DealId = dmax.DealId and
        d.PriceChangeDate = dmax.maxPriceChangeDate;

编辑:

如果您在deals(DealId, PriceChangeDate)上有索引,那么可能更有效的替代公式是:

select d.*
from deals d
where not exists (select 1
                  from deals d2
                  where d2.DealId = d.DealId and d2.PriceChangeDate > d.PriceChangeDate
                 )

效率来自于能够进行索引查找而不是聚合。缺点是查询很难解释(“选择每个Dealid的记录,其中没有PriceChangeDate大于该记录”。

答案 1 :(得分:0)

SELECT DealID, MAX(PriceChangeDate)
FROM Table1
GROUP BY DealID

SELECT t1.*
FROM Table1 t1
WHERE t1.PriceChangeDate = (SELECT MAX(t2.PriceChangeDate) 
                            FROM Table1 t2
                            WHERE t2.DealID = t1.DealID)