2012-05-29 31 views
1
Application (:id, :name) 

    has_many :steps 

Step (:id, application_id, :status) 

的樣本數據:Rails如何通過子表中的屬性來計算組的數量?

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 
+0

在合作例如你給的,我沒有看到子表的相關性......所以在你的問題'Step.select('sum(status),status')。group(:status)''會產生輸出工作 – Pierre

+0

@Pierre,授權r需要最後一步的計數。 – jdoe

+0

對,我的壞。花了我一段時間才明白,@ohho希望抓住每個應用程序的最新狀態並按狀態計數。 – Pierre

回答

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

使用
相關問題