1
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(*)申请状态的报告?IE

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

1 回答 1

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 中使用它

于 2012-05-29T10:05:08.400 回答