Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GROUP BY and COUNT using ActiveRecord

Refering to this: 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 

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

like image 706
Axil Avatar asked Aug 07 '15 13:08

Axil


People also ask

What does ActiveRecord base do?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending. Edit: as Mike points out, in this case ActiveRecord is a module...

What is ActiveRecord relation?

Whereas an instance of ActiveRecord::Relation is a representation of a query that can be run against your database (but wasn't run yet). Once you run that query by calling to_a , each , first etc. on that Relation a single instance or an array of ActiveRecord::Base instances will be returned.

What does ActiveRecord where return?

Returns a new relation, which is the result of filtering the current relation according to the conditions in the arguments.

What is ActiveRecord in Ruby on Rails?

What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.


1 Answers

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}  

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  
like image 107
thedanotto Avatar answered Oct 06 '22 06:10

thedanotto