2015-11-04 83 views

回答

1

Client.joins(:invoices).select('clients.id, clients.account_name, sum(invoices.balance) as balance').group('clients.id')

+0

是否有可能寫出來與聯接查詢? – Vasu

+1

'Client.joins(:invoices)'相當於'from clients c,invoices i where c.id = i.client_id'。 –

+1

但您也可以使用'find_by_sql'方法:'Clients.find_by_sql「SELECT c.id,c.account_name,sum(i.balance)作爲客戶端餘額c,發票i其中c.id = i.client_id GROUP BY c.id「'應該工作。 –