Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Join two tables count and sum from second table

Tags:

sql

join

count

sum

I have tow tables:

dealers with some fields and primary key id

and inquiries with following fields id dealer_id costs

There are several items in inquiries for every dealer and i have to count them and sum the costs. Now I have only the count with this statement:

SELECT a.*, Count(b.id) as counttotal
FROM dealers a
LEFT JOIN inquiries b on a.id=b.dealer_id
GROUP BY a.id
ORDER BY name ASC

but i have no idea how to sum the costs of table b for each dealer. Can anybody help? Thanks in advance

like image 339
Ole_S Avatar asked Mar 13 '13 14:03

Ole_S


2 Answers

SELECT a.*, Sum(b.id) as TotalCost
FROM dealers a
LEFT JOIN inquiries b on a.id=b.dealer_id
GROUP BY a.id
ORDER BY name ASC
like image 162
divyabharathi Avatar answered Oct 29 '22 13:10

divyabharathi


You could use two sub-queries:

SELECT  a.*
      , (SELECT Count(b.id) FROM inquiries I1 WHERE I1.dealer_id = a.id) as counttotal
      , (SELECT SUM(b.cost) FROM inquiries I2 WHERE I2.dealer_id = a.id) as turnover
FROM dealers a
ORDER BY name ASC

Or

SELECT  a.*
     , COALESCE(T.counttotal, 0) as counttotal   -- use coalesce or equiv. to turn NULLs to 0
     , COALESCE(T.turnover, 0) as turnover       -- use coalesce or equiv. to turn NULLs to 0
 FROM dealers a
 LEFT OUTER JOIN (SELECT a.id, Count(b.id) as counttotal, SUM(b.cost) as turnover
               FROM dealers a1 
               INNER JOIN inquiries b ON a1.id = b.dealer_id
              GROUP BY a.id) T
         ON a.id = T.id
ORDER BY a.name
like image 20
Mike Dinescu Avatar answered Oct 29 '22 12:10

Mike Dinescu