获取最小值的ID,按另一列分组

时间:2018-09-23 18:48:52

标签: mysql sql

我有一张这样的桌子

id, price, date
1, 200, 20180923
2, 100, 20180923
3, 300, 20180923
4, 300, 20180924
5, 200, 20180924
6, 100, 20180924

我想找到给定日期的最低价格,并检索ID。

所以SELECT id, MIN(price), date FROM table GROUP BY date将返回每个日期的最低价格,但不会告诉我它属于哪个id

此处的预期输出为

2, 100, 20180923
6, 100, 20180924

2 个答案:

答案 0 :(得分:2)

将其视为过滤而不是聚合。我会的:

select t.*
from t
where t.price = (select min(t2.price)
                 from t t2
                 where t2.date = t.date
                );

这样做的好处是可以利用(date, price)上的索引。

如果给定日期的最低价格重复,则会检索多行。

处理重复项的一种方法是将它们作为列表返回:

select t.date, min(t.price), group_concat(t.id) as ids
from t
where t.price = (select min(t2.price)
                 from t t2
                 where t2.date = t.date
                )
group by date;

答案 1 :(得分:0)

找到每个日期的最低价格分组。将此表用作派生表并与原始表联接,以获得对应于最低价格的完整行。

请尝试以下操作:

Select t1.* 
From your_table as t1 
Inner join (select t2.date, min(t2.price) as min_price 
                   From your_table as t2 
                   Group by t2.date) as t3 on t3.date = t1.date and t3.min_price = t1.price
相关问题