[英]GROUP BY with Distinct and Count for Active Record (Rails)
使用:Rails 2.3.8 ruby 1.8.7
如何將以下查詢轉換為Rails(活動記錄)
SELECT distinct source_code, count(source_code)
FROM table
GROUP BY 1
返回=>
| source_code | count |
| ABC | 16 |
| XYZ | 2 |
Model.find(:all, :select => "distinct source_code, count(source_code)",
:group => 1)
=> [Model source_code: "ABC">, Model source_code: "XYZ">]
如您所見,結果集中缺少計數。
您的SQL語句不需要DISTINCT
子句,因為GROUP BY
子句將返回不同的sourcecode
行。
在rails 2.3.x中,您可以獲得如下所示的期望結果:
Model.count(:group => :source_code)
# returns an ordered hash
{
"ABC" => 16,
"XYZ" => 2
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.