Okay I always have questioned this, but never really needed it until today.
Normally, I would grab all deals, go through them each and find the SUM(amount) from all the orders related to this deal. (PHP)
Then I would do a simple uasort() which works fine.
But now I need to do it all with a sql query.
This is what I have tried:
SELECT deals.ID, SUM(orders.amount) AS revenue FROM deals
JOIN orders ON (orders.deal_id = deals.id)
ORDER BY revenue DESC
Now this gives me one row, with a ‘random’ deal ID, and a bigger number in revenue.
I suspect this number in revenue is the SUM of ALL the amount columns, and not for this particular deal ID.
What I would like is a row for each deal ID, and with the right number in the column revenue, all the rows sorted DESC.
How would this be done? To sort the deals, out from their revenue (custom column) – which is the sum of all the amount columns from the rows for the respective deal id.
you lack
GROUP BYclause