Jump to content

inner join SUM


dee19802000

Recommended Posts

Hey I am having some difficulty trying to get an inner join to sum a column

 

SELECT quotes.quote_id, quotes.m_id, quotes.author, quotes.date_now, quotes.valid_date, quotes.comment, quotes.m_comment, quotes.reference, quotes_det.id_q, quotes_det.q_id, quotes_det.item_code, quotes_det.quantity, quotes_det.quote, quotes_det.active, SUM(quotes_det.quote) FROM (quotes LEFT JOIN quotes_det ON quotes_det.q_id=quotes.quote_id) WHERE quotes. m_id=%s GROUP BY quotes.reference

 

i keep getting 0 as my returned result.  What do i need o do to get the correct result?

 

Damain

Link to comment
Share on other sites

Hi

 

Not sure why you are getting 0, but you can't really use a SUM like that. You are grouping on a single column yet you are bringing back the details from multiple columns which are from different rows of the same table on which you are summing the column. MySQL will give you random row details (most flavours of SQL would just give you an error).

 

All the best

 

Keith

Link to comment
Share on other sites

Hi

 

Realistically something like this (note, not sure if quotes.m_id will be constant for a reference, if so you can take out the where from the subselect):-

 

SELECT quotes.quote_id, quotes.m_id, quotes.author, quotes.date_now, quotes.valid_date, quotes.comment, quotes.m_comment, quotes.reference, quotes_det.id_q, quotes_det.q_id, quotes_det.item_code, quotes_det.quantity, quotes_det.quote, quotes_det.active, quoteSum.SumOfQuotes
FROM quotes 
LEFT JOIN quotes_det 
ON quotes_det.q_id=quotes.quote_id 
LEFT JOIN (SELECT z.reference, SUM(y.quote) AS SumOfQuotes FROM quotes z LEFT JOIN quotes_det y ON y.q_id = z.quote_id WHERE quotes.m_id=%s  GROUP BY z.reference) quoteSum
ON quotes.reference = quoteSum.reference
WHERE quotes.m_id=%s 

 

Basically have a subselect to get all the sums of quotes per reference and then JOIN that with the results from the tables which get the rest of the fields.

 

All the best

 

Keith

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.