# Group By: Find a collection of the dates on which orders were created.
Order.select("date(created_at) as ordered_date, sum(price) as total_price").group("date(created_at)")
   SELECT date(created_at) as ordered_date, sum(price) as total_price FROM orders GROUP BY date(created_at) 

# Total of grouped items: To get the total of grouped items on a single query, call count after the group.
Order.group(:status).count
   SELECT COUNT (*) AS count_all, status AS status FROM "orders" GROUP BY status) 

# => { 'awaiting_approval' => 7, 'paid' => 12 }
# Having: SQL uses the HAVING clause to specify conditions on the GROUP BY fields. You can add the HAVING clause to the SQL fired by the Model.find by adding the having method to the find.
Order.select("date(created_at) as ordered_date, sum(price) as total_price"). group("date(created_at)").having("sum(price) > ?", 100)
   SELECT date(created_at) as ordered_date, sum(price) as total_price FROM orders GROUP BY date(created_at) HAVING sum(price) > 100 

Comments