【问题标题】:How to order results from a where statement如何从 where 语句中排序结果
【发布时间】:2014-02-19 12:49:27
【问题描述】:

我有一个投票模型和一个安置模型,用于跟踪员工在每个月底完成投票计数的位置。

投票模式

create_table "votes", :force => true do |t|
 t.integer  "phone_id",    :limit => 8
 t.integer  "employee_id"
 t.integer  "score"
end

展示位置架构

create_table "placements", :force => true do |t|
 t.integer  "employee_id"
 t.date     "month"
 t.integer  "votes_count", :default => 0
 t.integer  "position"
 t.integer  "total_score", :default => 0
end

我可以像这样按特定月份投票最多的顺序检索展示位置:

business.placements.where(month: month).order('votes_count desc')

我想按平均分(而不是多数票)的顺序获得展示位置。

平均分数可以这样计算:

average_score = placement.total_score/placement.votes_count

如何按 average_score 排序 where 语句?

【问题讨论】:

  • 你不能只添加一个平均分小数字段并在展示位置保存之前保存然后按该字段排序吗?
  • 你试过“Order BY votes_count DESC”吗?
  • @Baloo 我可以,但我认为这可能会浪费一些存储空间。但我认为你可能是对的。

标签: sql ruby-on-rails ruby


【解决方案1】:

试试这个

business.placements.where(month: month).order('total_score / votes_count desc')

【讨论】:

  • 此响应有效。刚在本地测试。如果您经常使用该选择,我建议您将该平均值保存在数据库中并按其排序。
【解决方案2】:

这有点远,但请尝试

business.placements.where(month: month).select('placements.*, (placements.total_score/placements.votes_count) AS average_score').order('average_score')

【讨论】:

    猜你喜欢
    • 2011-01-31
    • 2022-11-30
    • 1970-01-01
    • 2021-05-03
    • 1970-01-01
    • 2015-07-26
    • 2013-12-23
    • 2016-02-10
    • 2012-01-31
    相关资源
    最近更新 更多