[英]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. 我想要做的是创建一个SELECT,其中为每个唯一的DealID返回1行,该行是PriceChangeDate最新的行。
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: 在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;
EDIT: 编辑:
An alternative formulation, which might be more efficient if you have an index on deals(DealId, PriceChangeDate)
, is: 如果您有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
)
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"). 缺点是查询很难解释(“选择没有PriceChangeDate
大于该记录的每个Dealid
记录”)。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.