繁体   English   中英

Rails如何在子表中获取按属性分组的计数?

[英]Rails how to get count of group by attribute in a child table?

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM