使用sql语句的接受率

时间:2012-10-09 09:48:15

标签: 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% acceptance rate)

这将回归:史蒂夫,杰克和约翰。

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

也许可以用一个查询完成?

我正在使用rails,所以也可以通过rails来完成。

2 个答案:

答案 0 :(得分:3)

取决于您表示接受(真/假)的方式,如...

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

答案 1 :(得分:0)

您也可以尝试使用普通红宝石:

@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

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