【问题标题】:How to determine a number of grouped records in Rails?如何确定 Rails 中的分组记录数?
【发布时间】:2014-12-18 13:12:12
【问题描述】:

一个表有这样的结构和数据:

id | car     | location | ...
-----------------------------
1  | BMW     | US       | ...
2  | Audi    | US       | ...
3  | Audi    | US       | ...
4  | Porsche | CA       | ...
5  | Audi    | US       | ...

我正在以通常的方式加载和分组数据:

@cars = Cars.where('location = ?', location).group('car')

我需要在视图中显示一些分组数据 - 在这种情况下,我需要打印例如美国有多少数据;所以想要的输出是这样的:

BMW - 1 car
Audi - 3 cars

如何获取分组的行数?

【问题讨论】:

  • 不知道ruby,但在mysql中它会是select car,count(*) as total from table where location = 'US' group by car

标签: mysql ruby-on-rails ruby view group-by


【解决方案1】:
Car.where(location: location).group(:car).count #=> e.g. {'BMW' => 1}

仅供参考,您也可以按位置和汽车分组。

Car.group(:location, :car).count #=> e.g. {['US', 'BMW'] => 1}

【讨论】:

  • 完美,谢谢,第一个查询就是我需要的!只是一个问题——我使用第一个查询,我收到的结果是这样的——{'BMW' => 1}——但是有什么方法可以同时使用Car 模型的其他属性?因为现在,我在一个国家只有汽车制造商和一些汽车。谢谢。
  • 没问题。将我的帖子标记为答案,如果有帮助,请对此评论投赞成票。您可以通过“选择”子句添加其他属性。但是,我建议保持简单并执行location_car_count = Car.group(:location, :car).count,然后您可以迭代您的Car.where(location: location) 关系/数组。您将可以访问所有汽车属性并获得计数,您只需 car_count = location_car_count[[car.location, car.name]] 此处:codeshare.io/iGi4F
  • 嗯.. 这会起作用,但不会在单个查询中完成吗?现在有两个查询,这对于一个大表来说可能是个问题(我的表超过 100 万行)。
  • cars = Car.where(location: location).group(:car).select("#{Car.column_names}.join(',')", COUNT(car) AS car_count) 然后cars.first.car_count #=> what you want 但请记住,“汽车”不会包括数据库中的所有汽车,因为结果将被分组。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-04
  • 2022-01-10
  • 1970-01-01
  • 2020-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多