mysql - 计算具有不同列的行数

标签 mysql activerecord

我正在尝试使用 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)

最佳答案

尝试:

attempts.count('user_id', :conditions => "score = 100", :distinct => true)

更多信息:http://ar.rubyonrails.org/classes/ActiveRecord/Calculations/ClassMethods.html

关于mysql - 计算具有不同列的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5754236/

相关文章:

ruby-on-rails-3 - 如何让 ActiveRecord 查询忽略 nil 条件?

mysql - Codeigniter-计算一行中空列的数量

php - 在不转义的情况下将用户数据存储在数据库中

mysql - If then 记录多个条件的选择

mysql - 当没有该值时SQL选择默认值

ruby-on-rails - Rails 事件记录 : has_many error (NameError: uninitialized constant)

mysql - mysql docker容器的JDBC通信链接失败

mysql - 将 Sleep 添加到 mySQL 删除查询

design-patterns - Active Records vs. Repository - 优缺点?

ruby-on-rails - Rails - 在模型中查找具有特定值的条目的有效方法