繁体   English   中英

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

[英]How do I use mySQL to select results which have a maximum value for one column, grouped by another column?

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

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

PriceHistoryID, PriceChangeDate, DealID, Price

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

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

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

在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)指数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
                 )

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

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM