[英]rails 3 + activerecord: is there a single query to count(field1) grouped by field2?
I'm trying to find the best way to summarize the data in a table 我正在尝试找到汇总表中数据的最佳方法
I have a table Info with fields 我有一个带有字段的表信息
id
region_number integer (NOT associated with another table)
member_name string
member_active T/F
Members belong to a region, have a name, and are either active or not. 成员属于一个地区,有一个名字,并且活跃与否。
I'm wondering if there is a single query that will create a table with 3 columns, and as many rows as there are unique region_numbers: 我想知道是否有单个查询将创建一个具有3列的表,并且具有唯一的region_numbers的行数:
For each unique region_number:
region_number
COUNT of members in that region
COUNT of members in that region with active=TRUE
Suppose I have 50 regions, I see how to do it with 2x50 queries but that surely is not the right approach! 假设我有50个区域,我知道如何使用2x50查询,但这肯定不是正确的方法!
You can always group on several things if you're prepared to do a tiny bit of post-processing: 如果您准备进行一点后处理,则可以始终将几件事分组:
SELECT region_number, COUNT(*) AS instances, member_active
GROUP BY region_number, member_active
WHERE region_number IN ?
This allows you do to one query for all region numbers at the same time. 这样一来,您就可以一次查询所有区域号。 There will be one row for the T
values, one for the F
, but only if those are present. T
值将有一行, F
则有一行,但前提是存在它们。
If you see a case where you're doing a lot of queries that differ only in identifiers, that's something you can usually execute in one shot like this. 如果您看到正在执行很多仅在标识符上有所不同的查询的情况,那么通常可以像这样一次执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.