Skip to content

Commit 0885506

Browse files
committed
Add Total of grouped items to AR query interface on guides
[ci skip]
1 parent 3051356 commit 0885506

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

guides/source/active_record_querying.md

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -659,6 +659,40 @@ FROM orders
659659
GROUP BY date(created_at)
660660
```
661661

662+
### Total of grouped items
663+
664+
To get the total of grouped items on a single query call `count` after the `group`.
665+
666+
```ruby
667+
Order.group(:status).count
668+
# => { 'awaiting_approval' => 7, 'paid' => 12 }
669+
```
670+
671+
The SQL that would be executed would be something like this:
672+
673+
```sql
674+
SELECT COUNT (*) AS count_all, status AS status
675+
FROM "orders"
676+
GROUP BY status
677+
```
678+
679+
It is possible to do this count with multiple values, to do this only add the
680+
other column to `group`.
681+
682+
```ruby
683+
Order.group(:status, :delivery_method).count
684+
# => { ['awaiting_approval', 'regular'] => 5, ['awaiting_approval', 'fast'] => 2, ['paid', 'regular'] => 2, ['paid', 'fast'] => 10 }
685+
```
686+
687+
The SQL that would be executed would be something like this:
688+
689+
```sql
690+
SELECT COUNT (*) AS count_all, status AS status,
691+
delivery_method AS delivery_method
692+
FROM "orders"
693+
GROUP BY status, delivery_method
694+
```
695+
662696
Having
663697
------
664698

0 commit comments

Comments
 (0)