Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum on a left join SQL

Tags:

sql

mysql

I have two tables I wish to join on lets say table a and table b. Table b has many rows to table a's, table b contains prices (effectively a shopping basket). So what I want is all records from table a and the sum of the price from table b. I have tried

select a.*, sum(b.ach_sell) from bookings a 
left join pricing_line b on b.bookings = a.id

However this obviously doesn't do as I wish, it ends up with the total sum of all ach_sell (so one record is returned). Would someone kindly offer me a solution which would help? right now I am doing it programatically and I am pretty sure it could be done in SQL?

like image 297
Zoborg Avatar asked Jan 24 '11 12:01

Zoborg


1 Answers

Your direction is right, just add a group by clause to separate the a.id's, something like this:

select a.id, sum(b.ach_sell) 
from bookings a  
  left join pricing_line b 
on b.bookings = a.id 
group by a.id
like image 162
SWeko Avatar answered Sep 24 '22 22:09

SWeko