参考: 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约定是什么?
答案 0 :(得分:49)
Distinct
和Group By
会给您不同的结果。要获得您希望使用的结果
Person.all.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}
如上所述,group将返回哈希值。虽然不同只是返回总人数,见下文。
Person.all.distinct(:name).count
(0.4ms) SELECT DISTINCT COUNT(DISTINCT "people"."id") FROM "people"
=> 6
答案 1 :(得分:0)
请注意,接受的答案将返回哈希:
Tagging.joins(:tag).group(:name).size
(0.4ms) SELECT COUNT(*) AS count_all, `name` AS name FROM `taggings` INNER JOIN `tags` ON `tags`.`id` = `taggings`.`tag_id` GROUP BY `name`
=> {"applesauce"=>1, "oranges"=>2}
但是,如果要返回计数以及联接中来自不同表的一些列,该怎么办。然后,您还需要使用选择的ActiveRecord查询:
collection = Tagging.select('COUNT(*) as total, taggings.taggable_id, taggings.taggable_type').joins(:tag).where(taggable_type: 'LineItem', taggable_id: ['5cad0dcc3ed1496086000031', '5cad0dcd3ed1496086000081'] ).group(:name)
collection.each do |item|
puts item.taggable_id
puts item.total
end
5cad0dcc3ed1496086000031
1
5cad0dcc3ed1496086000031
2
使用第二种方法,您可以获取有关联接关系的其他详细信息,而无需任何其他查询或循环构造。
答案 2 :(得分:0)
另一个选择:
Person.select(:name, 'COUNT(name)').group(:name)
这会产生一系列具有属性计数的人