Mysql sql语句的接受率

Mysql sql语句的接受率,mysql,sql,ruby-on-rails,Mysql,Sql,Ruby On Rails,我有一个“建议”表,其结构如下: id(suggest_id) | author_id | accepted(true/false) 我想按最大接受率订购,例如: Jack had 10 suggests and he accepted 5 (50% acceptance rate) John had 20 suggests and he accepted 5 (25% acceptance rate) Steve had 10 suggests and he accepted 8 (80%

我有一个“建议”表,其结构如下:

id(suggest_id) | author_id | accepted(true/false)
我想按最大接受率订购,例如:

Jack had 10 suggests and he accepted 5 (50% acceptance rate)
John had 20 suggests and he accepted 5 (25% acceptance rate)
Steve had 10 suggests and he accepted 8 (80% acceptance rate)
这将返回:史蒂夫,杰克和约翰

我认为它可能必须有两个SQL查询,一个用于建议数,另一个用于
accepted=true

也许一个查询就可以完成


我使用的是rails,所以它也可以由rails来完成。

取决于您如何表示接受(真/假)的内容,例如

select author_id, 
    sum(case when accepted ='true' then 1 else 0 end), 
    100.0*sum(case when accepted ='true' then 1 else 0  end)/count(*)
from yourtable
group by author_id
order by 100.0*sum(case when accepted ='true' then 1 else 0 end)/count(*) desc

取决于你是如何表达被接受(真/假)的,比如

select author_id, 
    sum(case when accepted ='true' then 1 else 0 end), 
    100.0*sum(case when accepted ='true' then 1 else 0  end)/count(*)
from yourtable
group by author_id
order by 100.0*sum(case when accepted ='true' then 1 else 0 end)/count(*) desc

您也可以尝试使用纯ruby:

@authors_by_acceptance_rate = Array.new
@authors = Author.all
@authors.each do |author|
  @suggests = Suggest.find_by_author_id(author.id)
      accepted = 0
  @suggests.each do |suggest|
    if suggest.accepted
      accepted = accepted + 1
    end
  end
  acceptance_rate = accepted/@suggests.count
  @authors_by_acceptance_rate.push('name' => @author.name, 'accepted' =>     acceptance_rate)   
end
return @authors_by_acceptance_rate

我还没有测试过这个,所以不能保证它正常工作…

您也可以尝试使用纯ruby:

@authors_by_acceptance_rate = Array.new
@authors = Author.all
@authors.each do |author|
  @suggests = Suggest.find_by_author_id(author.id)
      accepted = 0
  @suggests.each do |suggest|
    if suggest.accepted
      accepted = accepted + 1
    end
  end
  acceptance_rate = accepted/@suggests.count
  @authors_by_acceptance_rate.push('name' => @author.name, 'accepted' =>     acceptance_rate)   
end
return @authors_by_acceptance_rate

我还没有测试过这个,所以不能保证它能正常工作…

使用
HAVING
而不是
WHERE
来过滤聚合。例:
计数(*)>10
谢谢!顺便说一句,GROUP BY必须在使用
HAVING
而不是
WHERE
之前进行筛选以筛选聚合。例:
计数(*)>10
谢谢!顺便说一句,分组前必须