2015-12-26 30 views
0

如果我运行下面的查询,ActiveRecord - 如何使用JOINS,GROUP和SELECT只有特定的列?

@top_companies    = Shipment.joins(:company) 
             .where('...') 
             .group('companie.name') 
             .order('count_all DESC').limit(10).count 

输出出货格式的公司名称=>计数:

"Company name"=>12, ...} 

但我需要从companies也获取其他列表,就像id等等,所以我试过了:

@top_companies    = Shipment.joins(:company) 
             .select('shipments.*, companies.id, companies.name, companies.name_slug') 
             .where('...') 
             .group('companie.name') 
             .order('count_all DESC').limit(10).count 

但输出保持不变 - 为什么?如何将另一列添加到输出哈希?

+0

哈希格式化输出看起来你有一个.count在链的踪迹。 –

+0

是的,它在那里......当我复制代码块时,我错过了它,会修改OP。 – user984621

回答

-1

尝试使用pluck而不是select。

Client.where(active: true).pluck(:id) 
# SELECT id FROM clients WHERE active = 1 
# => [1, 2, 3] 

Client.distinct.pluck(:role) 
# SELECT DISTINCT role FROM clients 
# => ['admin', 'member', 'guest'] 

Client.pluck(:id, :name) 
# SELECT clients.id, clients.name FROM clients 
# => [[1, 'David'], [2, 'Jeremy'], [3, 'Jose']] 

http://guides.rubyonrails.org/active_record_querying.html#pluck

1

你可以简单地将Companies列添加到group声明:

@top_companies = Shipment.joins(:company) 
        .where('...') 
        .group('companies.id, companies.name, companies.name_slug') 
        .order(count_all: :desc).limit(10).count 

而且因为你是分组Shipments,如果你希望包括它的列,你需要告诉SQL你希望数据如何汇总:

@top_companies = Shipment.joins(:company) 
        .where('...') 
        .select('AVG(shipments.delivered_in), COUNT(*), companies.id, companies.name, companies.name_slug') 
        .group('companies.id, companies.name, companies.name_slug') 
1

需要相应查询的名称和name_slug的Company对象是这样的:

@top_companies = Shipment.joins(:company) 
       .select('count(*) as shipments_count, companies.id as company_id, companies.name as company_name, companies.name_slug as company_name_slug') 
       .where('...') 
       .group('companie.name') 
       .order('count_all DESC').limit(10) 

@top_companies.map(&:shipments_count) 
# this will return the shipment count 

@top_companies.map(&:company_name_slug) 
# this will return the company name slug corresponding to each group of shipment by company name 

现在需要只使用@top_companies.map,能写里面map任何逻辑来获得所需的输出。