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
If I am understanding your question, all you need to do is add a
SUM()
:My suggestion would be to use a subquery to get the
count
and thesum
:I am guessing from your original query that you are using MySQL. I would suggest using a subquery because MySQL uses an extension to GROUP BY which allows items in a select list to be nonaggregated and not included in the
GROUP BY
clause. This however can lead to unexpected results because MySQL can choose the values that are returned. (See MySQL Extensions to GROUP BY)From the MySQL Docs:
Just add
, Sum(b.costs) as costsTotal
to your select list.makeing a sub table, with the desired fields, and joining it, not the full table will make the things easyer
sorry for the bar spelling if any
You could use two sub-queries:
Or