引用这个: Is there any difference between GROUP BY and DISTINCT
Given a table that looks like this:
name
------
barry
dave
bill
dave
dave
barry
john
This query:
SELECT name, count(*) AS count FROM table GROUP BY name;
Will produce output like this:
name count
-------------
barry 2
dave 3
bill 1
john 1
对于 ActiveModel 使用 COUNT 执行 GROUP BY 的正确 Rails 约定是什么?
最佳答案
Distinct
和 Group By
会给你不同的结果。要获得您期望的结果,您需要使用
Person.group(:name).count
(1.2ms) SELECT COUNT(*) AS count_all, name AS name FROM "people" GROUP BY "people"."name"
=> {"Dan"=>3, "Dave"=>2, "Vic"=>1}
如上所示,组将以散列形式返回内容。虽然 distinct 只返回总人数,如下所示。
Person.distinct(:name).count
(0.4ms) SELECT DISTINCT COUNT(DISTINCT "people"."id") FROM "people"
=> 6
关于sql - GROUP BY 和 COUNT 使用 ActiveRecord,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31879150/