dannymcc
dannymcc

Reputation: 3814

Rails sql query, filtering thousands of records and summing up one column

I have a database table with thousands of rows. I would like to run a report that basically lists all clients who have spent more than £2,000 with us.

The table has a lot of columns, but the ones I am interested are as follows:

======================================================
|  ClientKey | PVID | ShortText           | Payments |
======================================================
|  13276     | 76668| Paid by PET HEALTH  | 56.79    |
|  12893     | 62368| Paid by PET HEALTH  | 42.79    |
|  23782     | 87468| Paid by PET HEALTH  | 26.29    |
|  23246     | 79868| Paid by PET HEALTH  |-16.52    |
======================================================

I need to group the rows by ClientKey and sum up the Payments columns. Then I need to filter them by removing anything where the Payments column sum is less than £2,000. I also need to ignore any rows where the PVID is 44444.

So far I know I will need to have something similar to the following:

@clinical = Clinical.where("ShortText LIKE 'Paid by PET HEALTH' AND PVID != 44444")

That takes care of filtering the rows down to exclude anything with a PVID of 44444 and only showing rows where the ShortText contains Paid by PET HEALTH.

I can't get my head around how to sum up the payments column for each of the ClientKey's.

The end result I would like is the ability to do this:

Client Key 13276 has spent £99,999 so far.
Client Key 21342 has spent £3,200 so far.
Client Key 32312 has spent £2,110 so far.

Any help and/or pointers would be appreciated!

Upvotes: 1

Views: 320

Answers (1)

Salil
Salil

Reputation: 9722

You can try:

Clinical.select("ClientKey as client_key, sum(Payments) as total_payments").group("ClientKey").where("ShortText LIKE 'Paid by PET HEALTH' AND PVID != 44444")

For more information about the grouping, refer rails guide - ActiveRecord Query Interface

Upvotes: 3

Related Questions