我正在尝试使用Active Record计算具有不同列的行数。
以下SQL有效,并为我提供了正确的结果:
SELECT COUNT(DISTINCT(user_id)) FROM attempts WHERE score = 100 AND problem_id = 1
但是这段代码会引发ActiveRecord::StatementInvalid
错误:
attempts.where(:score => 100).count(:distinct => :user_id)
答案 0 :(得分:1)
尝试:
attempts.count('user_id', :conditions => "score = 100", :distinct => true)
更多信息:http://ar.rubyonrails.org/classes/ActiveRecord/Calculations/ClassMethods.html