简体   繁体   中英

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

Not sure how much sense the question makes, but hopefully I can explain with an example.

I have a table with the following columns:

PriceHistoryID, PriceChangeDate, DealID, Price

These are primary key, a date, foreign key, and a price. This is set up so that each time a price is changed for a 'Deal', a new row is created in this table.

What I would like to do is create a SELECT where 1 row is returned for each unique DealID, and that row is where the PriceChangeDate is the latest.

I feel like I've done something like this before, and it doesn't seem that difficult, but I am drawing a blank. Thanks for any help!

In MySQL, you can do this using a subquery and join:

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;

EDIT:

An alternative formulation, which might be more efficient if you have an index on deals(DealId, PriceChangeDate) , is:

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

The efficiency comes from being able to do an index lookup instead of an aggregation. The downside is that the query is hard to explain ("choose the record for each Dealid where there is no PriceChangeDate larger than that record").

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

or

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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