简体   繁体   中英

How to sum columns from two related tables

I have two tables. Invoices and invoice_items . I am trying to get the sum of total_payment and total quantity for each client. I tried this query:

SELECT client_id,
sum(total_amount), sum(it.quantity) as days_hired
FROM  `invoices` `iv`
  join invoice_items it on  it.invoice_id=iv.invoice_id
group by client_id, it.invoice_id

But for client_id 14, I am getting total payment as 1908 instead of 636. Looks like the sum of this column gets repeated for every invoie_item. Any help will be appreciated.

invoices

invoice_id    client_id    total_payment
    36        13           530
    38        14           636


invoice_items

invoice_id    user_id      quantity     
36            2            2
38            3            2
38            4            2
38            5            2

Expected output:

13     530       2
14     636       6

You can try below -

SELECT client_id, sum(total_amount) as toal_amount, sum(it.quantity) as total_quantity
FROM  `invoices` `iv`
join
(
 select invoice_id,sum(quantity) as quantity from invoice_items group by invoice_id
)it on  it.invoice_id=iv.invoice_id
group by client_id, it.invoice_id

Try:

select i.*, ii.total_quantity
from invoices i
join (
  select invoice_id, sum(quantity) total_quantity from invoice_items
  group by invoice_id
) ii on i.invoice_id = ii.invoice_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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