我有一个包含数千行的数据库表。我想发一份报告,基本上列出了所有花费超过2000英镑的客户。
该表有很多列,但我感兴趣的是如下:
======================================================
| 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 |
======================================================
我需要通过ClientKey对行进行分组,并总结Payments列。然后我需要通过删除Payments列总和小于2,000英镑的任何内容来过滤它们。我还需要忽略PVID为44444的任何行。
到目前为止,我知道我需要有类似以下的内容:
@clinical = Clinical.where("ShortText LIKE 'Paid by PET HEALTH' AND PVID != 44444")
负责过滤行以排除任何PVID为44444的行,并仅显示ShortText包含PET HEALTH付费的行。
我无法理解如何总结每个ClientKey的付款列。
我想要的最终结果是能够做到这一点:
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.
任何帮助和/或指示都将不胜感激!
答案 0 :(得分:3)
您可以尝试:
Clinical.select("ClientKey as client_key, sum(Payments) as total_payments").group("ClientKey").where("ShortText LIKE 'Paid by PET HEALTH' AND PVID != 44444")
有关分组的详细信息,请参阅rails guide - ActiveRecord Query Interface