简体   繁体   中英

sum column with sum of joined table

I have two tables appointments and line_items.

appointments 
id integer primary key 
price decimal

line_items 
id integer primary key 
price decimal 
appointment_id integer foreign key

I need to get sum of appointments.price with sum of associated sum of line_items price.

For example, I have 2 appointments

id price 
1 10 
2 15

and line items

id price appointment_id
1  10    1
2  15    1
3  10    2
3  20    2

The total result should be (10 + (10 + 15)) + (15 + (10 + 20))

Currently I am trying this query. But it doesn't work.

SELECT SUM(appointments.price + sum(line_items.price)) AS total_sum
FROM `appointments`
  INNER JOIN 'line_items' ON 'line_items'.'appointment_id' = 'appointments'.'id'

What is best approach for this? Subquery for sum of line_items.price or joining sum line_items.price. Or there is another better solution?

Thanks in advance!

I think what you are looking for is a SUM() GROUP BY in a derived table and then a join with appointments . Something like this.

SELECT SUM(appointments.price + line_items.price) AS total_sum
FROM appointments
 INNER JOIN 
(
SELECT line_items.appointment_id,SUM(price) as price
line_items
GROUP BY appointment_id 
) line_items ON line_items.appointment_id = appointments.id

This should give you what you're looking for, it seems you were close to the answer:

SELECT SUM(app.price + IFNULL(li.price,0)) AS total_sum
FROM appointments app
  LEFT JOIN 
  (Select appointment_id, Sum(price) price from line_items group by appointment_id) li on li.appointment_id = app.id

Try this

 SELECT appointments.id,(appointments.price + sum(line_items.price)) AS total_sum
 FROM appointments
 INNER JOIN line_items ON line_items.appointment_id = appointments.id
 group by appointments.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