diff options
author | Mauro George <maurogot@gmail.com> | 2014-06-01 10:58:24 -0300 |
---|---|---|
committer | Mauro George <maurogot@gmail.com> | 2014-06-01 10:58:24 -0300 |
commit | 08855064cd1b98cf0c00f902de89a94d0564c459 (patch) | |
tree | b3b463c729c67250c21fc82ded814c12cd1e9a1d | |
parent | 3051356a8005518392f3414184daf933f5597092 (diff) | |
download | rails-08855064cd1b98cf0c00f902de89a94d0564c459.tar.gz rails-08855064cd1b98cf0c00f902de89a94d0564c459.tar.bz2 rails-08855064cd1b98cf0c00f902de89a94d0564c459.zip |
Add Total of grouped items to AR query interface on guides
[ci skip]
-rw-r--r-- | guides/source/active_record_querying.md | 34 |
1 files changed, 34 insertions, 0 deletions
diff --git a/guides/source/active_record_querying.md b/guides/source/active_record_querying.md index ee8cf4ade6..b2d71d4be8 100644 --- a/guides/source/active_record_querying.md +++ b/guides/source/active_record_querying.md @@ -659,6 +659,40 @@ 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`. + +```ruby +Order.group(:status).count +# => { 'awaiting_approval' => 7, 'paid' => 12 } +``` + +The SQL that would be executed would be something like this: + +```sql +SELECT COUNT (*) AS count_all, status AS status +FROM "orders" +GROUP BY status +``` + +It is possible to do this count with multiple values, to do this only add the +other column to `group`. + +```ruby +Order.group(:status, :delivery_method).count +# => { ['awaiting_approval', 'regular'] => 5, ['awaiting_approval', 'fast'] => 2, ['paid', 'regular'] => 2, ['paid', 'fast'] => 10 } +``` + +The SQL that would be executed would be something like this: + +```sql +SELECT COUNT (*) AS count_all, status AS status, +delivery_method AS delivery_method +FROM "orders" +GROUP BY status, delivery_method +``` + Having ------ |