简体   繁体   English

Rails Active Record CrossTab查询

[英]Rails Active Record CrossTab Query

A vehicle has_many services. 车辆有很多服务。 services has_many types (0,1,2,3,4). 服务具有多种类型(0,1,2,3,4)。

I need to write a query that shows the mileage reading of when each type of service was last completed for a vehicle. 我需要编写一个查询,以显示上一次完成每种服务的车辆的里程读数。

In my MS ACCESS days this was a simple crosstab (transform) query. 在我的MS ACCESS时代,这是一个简单的交叉表(转换)查询。 Could someone point me in the right direction in the rails environment? 有人可以指出我在Rails环境中的正确方向吗? Thanks 谢谢

This is the long hand version of what I'm trying to collate: 这是我要整理的长篇版:

        @a_last = v.services.maximum(:mileage_closed, :conditions => ["closed = TRUE AND service_type_id > 0"])
        @b_last = v.services.maximum(:mileage_closed, :conditions => ["closed = TRUE AND service_type_id > 1"])
        @c_last = v.services.maximum(:mileage_closed, :conditions => ["closed = TRUE AND service_type_id > 2"])
        @d_last = v.services.maximum(:mileage_closed, :conditions => ["closed = TRUE AND service_type_id > 3"])
        @e_last = v.services.maximum(:mileage_closed, :conditions => ["closed = TRUE AND service_type_id > 4"])

Thanks! 谢谢!

The simple answer is to iterate through a range and collect your results: 简单的答案是遍历一个范围并收集结果:

mileages = (0..4).collect do |service_type|
  vehicle.services.maximum(:mileage_closed, :conditions => ["CLOSED = TRUE AND SERVICE_TYPE_ID = #{service_type}"]
end

I'm guessing you mean to search the service type id with an equals instead of a more than. 我猜您的意思是用等号而不是大于号搜索服务类型ID。

This will, however, make 5 sql statements when it is run. 但是,这将在运行时生成5条sql语句。 You'll probably find this doesn't effect performance too badly. 您可能会发现这不会对性能产生太大影响。 If performance does become an issue, a different approach would be to write an SQL statement to find your results (it'll be grouped by vehicle_id and service_type_id, then run a MAX() on the mileage_closed column) and make that a view in your database. 如果性能确实成为问题,则可以采用另一种方法编写一条SQL语句以查找结果(将其按Vehicle_id和service_type_id分组,然后在Mileage_closed列上运行MAX()),然后在您的数据库。 Then you should be able to find these results in a single database round trip. 然后,您应该能够在一次数据库往返中找到这些结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM