GROUP BY 和 COUNT 使用 ActiveRecord [英] GROUP BY and COUNT using ActiveRecord

查看:20
本文介绍了GROUP BY 和 COUNT 使用 ActiveRecord的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

参考此:GROUP BY 和 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 约定是什么?

What is the correct Rails convention here for ActiveModel to perform a GROUP BY with COUNT?

推荐答案

DistinctGroup By 会给你不同的结果.为了获得您希望使用的结果

Distinct and Group By are going to give you different results. To get the results you expect you'll want to use

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} 

如上所示,group 会以散列形式返回内容.虽然distinct 只返回总人数,见下图.

Seen above, group will return things as a hash. While distinct just returns the number of people in total, seen below.

Person.distinct(:name).count
(0.4ms)  SELECT DISTINCT COUNT(DISTINCT "people"."id") FROM "people"
=> 6 

这篇关于GROUP BY 和 COUNT 使用 ActiveRecord的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆