使用相对ID在表中查找最大值

时间:2013-05-26 21:56:19

标签: mysql sql

假设有一个表人( ID ,.....,n_success,n_fails)

喜欢

 ID  n_success   n_fails

 a1      10         20
 a2      15         10
 a3      10         1

我想创建一个查询,返回最大n_success /(n_success + n_fails)的人的ID。

在这种情况下,我想得到的输出是:

  a3   0.9090909091

我试过了:

  select ID,(N_succes/(n_success + n_fails)) 'rate' from person

使用此查询我有每个ID具有相对成功率

  select ID,MAX(N_succes/(n_success + n_fails)) 'rate' from person

使用此查询只有1行正确率但不正确的ID

我该怎么办?

4 个答案:

答案 0 :(得分:1)

MS SQL

SELECT TOP 1 ID, (`n_success` / (`n_success` + `n_fails`)) AS 'Rate' FROM persona
ORDER BY (n_success / (n_success + n_fails)) DESC

的MySQL

SELECT `ID`, (`n_success` / (`n_success` + `n_fails`)) AS 'Rate' FROM `persona`
ORDER BY (`n_success` / (`n_success` + `n_fails`)) DESC
LIMIT 1

答案 1 :(得分:1)

这取决于您的SQL方言,但在T-SQL中它将是:

SELECT TOP 1 p.ID, p.n_success / (p.n_success + p.n_fails) AS Rate
FROM persona p
ORDER BY p.n_success / (p.n_success + p.n_fails) DESC

您可以根据需要改变其他方言(例如,对MySql和SQLite使用LIMIT 1。)

答案 2 :(得分:1)

已有很多答案。检查SQL Fiddle上的工作代码,并使用上次编辑所需的输出。

SELECT `ID`, `n_success` 'rate'
  FROM `persona`
 ORDER BY (`n_success` / (`n_success` + `n_fails`)) DESC
 LIMIT 1

答案 3 :(得分:1)

select id, (n_success/(n_success + n_fails)) as rate from person
where (n_success/(n_success + n_fails)) = 
    (select max(n_success/(n_success + n_fails)) from person)