如果我运行以下查询,
@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 :(得分: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 :(得分:1)
您需要在Company
对象上相应地查询名称和name_slug,如下所示:
@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
内编写任何逻辑以获得所需的输出。
答案 2 :(得分:-2)
尝试使用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