使用聚合MIN时,我无法让mysql返回最后一行

时间:2013-11-06 23:37:20

标签: mysql sql greatest-n-per-group

我在mysql中使用MIN函数返回列的最小值 - 让我们调用它的价格,但是我也希望显示具有最小价格值的特定行的各种其他列。到目前为止,我有以下内容:

SELECT underlying,volatility FROM shares
where (id,price) IN (
    SELECT id,MIN(price) FROM shares
    where DATE(issueDate) >= DATE(NOW())
    group by id
 )

这几乎可以工作,但它返回多行,我只希望显示最后一行,有人可以帮我这个吗?

3 个答案:

答案 0 :(得分:1)

我想我已经解决了这个问题,需要一段时间才能执行,所以我将首先添加一个新索引:

SELECT underlying,volatility,price FROM shares
where (id,price) IN (
    SELECT id,MIN(price) FROM shares
    where DATE(issueDate) >= DATE(NOW())
    group by id
) order by price asc limit 1;

答案 1 :(得分:0)

SELECT underlying,volatility FROM shares
where (id,price) IN (
    SELECT 
        SUBSTRING_INDEX(GROUP_CONCAT(id ORDER BY price ASC), ',', 1) AS id,
        MIN(price) FROM shares
    where DATE(issueDate) >= DATE(NOW())
    group by id
 )

答案 2 :(得分:0)

拥有子句可以解决问题,请检查我的解决方案

select volatility,underlying, min(price) as min_price  from shares
where DATE(issueDate) >= DATE(NOW())
group by issueDate
having min_price = min(price);

fiddle example