I have a table: "ID name c_counts f_counts "
and I want to order all the record by sum(c_counts+f_counts)
but this doesn't work:
SELECT * FROM table ORDER BY sum(c_counts+f_counts) LIMIT 20;
The SUM function will add up all rows, so the order by clause is useless, instead you will have to use the group by clause.
An aggregate function cannot be used directly in: an ORDER BY clause. Attempting to do so generates an SQLCODE -73 error. However, you can use an aggregate function in an ORDER BY clause by specifying the corresponding column alias or selectItem sequence number.
SUM() function with group bySUM is used with a GROUP BY clause. The aggregate functions summarize the table data. Once the rows are divided into groups, the aggregate functions are applied in order to return just one value per group.
Don'y forget that if you are mixing grouped (ie. SUM) fields and non-grouped fields, you need to GROUP BY one of the non-grouped fields.
Try this:
SELECT SUM(something) AS fieldname FROM tablename ORDER BY fieldname
OR this:
SELECT Field1, SUM(something) AS Field2 FROM tablename GROUP BY Field1 ORDER BY Field2
And you can always do a derived query like this:
SELECT f1, f2 FROM ( SELECT SUM(x+y) as f1, foo as F2 FROM tablename GROUP BY f2 ) as table1 ORDER BY f1
Many possibilities!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With