0

我有一个具有以下结构的“建议”表:

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来完成。

4

2 回答 2

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
于 2012-10-09T09:52:01.420 回答
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

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

于 2012-10-10T17:40:31.220 回答