我目前正在使用min()
查找MYSQL数据库中的最低值。
我怎样才能找到第二低的值?
'select Date, Horse, ParentID, min(odds2)
from horsesrp
where odds2 < 3.1 and odds2 > 1.9
and Date = "'.$id.'"
AND Track IN ("Kempton (AW)","Wolverhampton (AW)")
group by ParentID order by ParentID'
请注意我仍需要通过ParentID订购,因为我想获得每个parentid的第二低赔率
所以我的数据库看起来像:
Racetime Odds
13:05 2
13:05 2.4
13:05 3
13:05 5
13:30 3
13:30 5
13:30 9
13:30 13.5
14:00 1.14
14:00 1.19
14:00 2
14:00 4
我想找到每次的第二个最低值,但它必须介于1和2.9之间
Racetime Odds
13:05 2.4
14:00 1.19
所以上面的输出是
由于
艾玛
答案 0 :(得分:7)
SELECT * FROM table_name ORDER BY id ASC LIMIT 1, 1
答案 1 :(得分:3)
这是另一个问题的例子,
Product_id reg_price sale_price
244 50 40
244 45 40
244 45 0
244 40 0
要找到第二低的sale_price,
SELECT
MIN(NULLIF(sale_price, 0))
FROM `table`
WHERE product_id = 244;
编辑1
所以在你的情况下,
SELECT
MIN(NULLIF(odds2,0))
FROM horserp
order by ParentID asc;
这应该由ParentID排序......
编辑2 - 第二次查询
Select TOP 1 odds2 as '2nd lowest'
from (SELECT DISTINCT TOP 2 odds2 from horserp ORDER BY odds2 ASC)
a ORDER BY odds2 DESC
编辑3 - 进一步嵌套第二个查询
select *
from (Select TOP 1 odds2 as '2nd lowest'
from (SELECT DISTINCT TOP 2 odds2 from horserp ORDER BY odds2 ASC) a ORDER BY odds2 DESC)
order by ParentID desc;
答案 2 :(得分:3)
您可以通过多种方式获得第二低的值。如果您从这个查询开始:
select Date, Horse, ParentID, min(odds2)
from horsesrp
where odds2 < 3.1 and odds2 > 1.9 and Date = "'.$id.'" AND
Track IN ("Kempton (AW)","Wolverhampton (AW)")
group by ParentID
order by ParentID;
然后最简单的方法是使用substring_index()
/ group_concat()
技巧:
select Date, Horse, ParentID, min(odds2),
substring_index(substring_index(group_concat(odds2) order by odds2, ',', 2), ',', -1) as second_odds
from horsesrp
where odds2 < 3.1 and odds2 > 1.9 and Date = "'.$id.'" AND
Track IN ('Kempton (AW)', 'Wolverhampton (AW)')
group by ParentID
order by ParentID;
但是,我对你的样本数据有什么不了解。查询中没有racetime
。
答案 3 :(得分:1)
<强>查询强>
Select TOP 1 Salary as '2nd Lowest Salary'
from (SELECT DISTINCT TOP 2 Salary from Employee ORDER BY Salary ASC)
a ORDER BY Salary DESC
答案 4 :(得分:1)
试试这个
SELECT ParentID, Horse, Date, min(odds2) FROM
(
select DISTINCT HP.ParentID, HP.Horse, HP.Date, HP.odds2, SUB.min_odd from
horsesrp HP INNER JOIN
(
SELECT parentID,Date,Horse,min(odds2) min_odd FROM horsesrp GROUP BY parentID,parentID,Date,Horse
) SUB ON HP.ParentID = SUB.ParentID AND HP.Date = SUB.Date AND HP.Horse = SUB.Horse WHERE HP.odds2 < 3.1 and HP.odds2 > 1.9
and HP.Date = "'.$id.'"
AND HP.Track IN ("Kempton (AW)","Wolverhampton (AW)") AND HP.odds2>SUB.min_odd
) SUB_END
GROUP BY ParentID, Horse, Date
ORDER BY ParentID
这里的问题是,由于您获得的第二低,如果您只有一行特定的parentID,您将看不到最小值。
代码可能有错误,请告诉我。