Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ORDER BY a SUM() in MySQL?

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;

like image 715
lovespring Avatar asked Aug 21 '09 02:08

lovespring


People also ask

Can we use SUM function in ORDER BY clause?

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.

Can you ORDER BY aggregate function?

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.

How do you sum in a GROUP BY?

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.


1 Answers

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!

like image 127
gahooa Avatar answered Sep 28 '22 19:09

gahooa