Group By and Having
# 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)") |
# Total of grouped items: To get the total of grouped items on a single query, call count after the group. Order.group(:status).count # => { '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) |
Comments
Related