Rails如何在子表中获取group by属性的计数?

时间:2012-05-29 08:25:04

标签: ruby-on-rails activerecord

Application (:id, :name)

  has_many :steps

Step (:id, application_id, :status)

示例数据:

  Application       Name
 -------------  ------------
    1              'Peter'
    2              'Paul'
    3              'Mary'

  Step    Application ID    Status
 ------   --------------   -------------
    1           1           'new'
    2           2           'new'
    3           1           'in-review'
    4           2           'in-review'
    5           2           'completed'
    6           3           'new'
    7           3           'in-review'

如何获得有关应用程序最新状态count(*)的报告?即。

   Status       Count       
 ------------- -------
  'in-review'     2
  'completed'     1

1 个答案:

答案 0 :(得分:1)

HAVING,MAX似乎没有使用mysql 5.1

这个似乎正在运作

select status, count(status) as "count"
from (
        select status 
        from (
                select * from steps order by created_at desc
             )
        steps_sorted 
        group by application_id
     )
latest_statuses 
group by status;

您可以在Step.find_by_sql

中使用它