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

4
我有这样一张表:
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

如果在给定日期上有多个ID具有相同的最小值,您希望返回什么? - Gordon Linoff
2个回答

8
把这看作是过滤而不是聚合。我会这样做:
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;

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接