I have the following statement. The results come back but the records aren’t sorted. What am I doing wrong?
SELECT *
FROM (
SELECT name, date, SUM(volume) AS sumVolume, SUM(value) AS sumValue
FROM table
WHERE id = 12
) AS TempTable
ORDER BY date DESC
This query won’t work as you intended. Using
SUM(which is an AGGREGATE function) within your derived table is going to give you exactely ONE row back – unless you start toGROUP BYanother column.In your example, even if you’d group by
idyou’d still only get a single row, though (that’s because you’d group by a single id). Alter theWHEREstatement to include more ids and group them within the derived table.Also, take a look at the MySQL manual on the various aggregate functions to get a feeling of what they do.
Regards
EDIT
Since the OP’s requirements have somewhat become clear, I’ll try to help him with his query: