9

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?

1
  • is it practical to do a union? Jan 24, 2011 at 12:41

5 Answers 5

17

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
0
2

Group on the fields from the bookings table:

select a.this, a.that, sum(b.ach_sell)
from bookings a 
left join pricing_line b on b.bookings = a.id
group by a.this, a.that
1
  • I'd add "sum(b.ach_sell) as summed_column" for easier addressing.
    – MeanEYE
    Jan 24, 2011 at 12:41
2
select a.*, sum(b.ach_sell) as sum_column 
from bookings a 
  left join pricing_line b
         on b.bookings = a.id
group by a.id

Every time you use funcions of aggregation (SUM, COUNT, MIN, MAX, AVG) you need to group by some other set of fields (tipically the id) on which you don't apply an aggregation function.

0

You need to GROUP BY something if you don't want just a single result. Possibly?

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

Other RDBMSs would insist on you having the entire column list in the GROUP BY but MySQL doesn't.

0

If you have many columns in select.

Like this:

SELECT
    co.checkOutOrderID,
    com.companyCode,
    sd.serviceDispatchCode,
    cu.customerName,
    com.companySimp,
    ISNULL(SUM (sdlp.partsModelPrice * sdlp.partsModelNum), 0) AS total
FROM
    checkoutorder co
LEFT JOIN 
    servicedispatchorder sd ON sd.serviceDispatchID = co.serviceDispatchID
LEFT JOIN 
    customer cu ON cu.customerID = co.customerID
LEFT JOIN 
    company com ON com.companyID = co.companyID
LEFT JOIN 
    servicedispatchlinkparts sdlp ON sdlp.serviceDispatchID = sd.serviceDispatchID
GROUP BY
    sd.serviceDispatchID, co.checkOutOrderID, 
    com.companyCode, sd.serviceDispatchCode,
    cu.customerName, com.companySimp

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.