Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL Order By Sum of Columns

Any idea on how to order the results of a MYSQL query by the sum of two columns rather than by a single column?

Select * FROM table ORDER BY (col1+col2) desc

I know that won't work., but I hope it conveys what I want to do fairly well.

Thanks!

like image 812
djs22 Avatar asked Jun 17 '10 05:06

djs22


People also ask

Can you ORDER BY SUM SQL?

Use ORDER BY if you want to order rows according to a value returned by an aggregate function like SUM() . The ORDER BY operator is followed by the aggregate function (in our example, SUM() ). DESC is placed after this function to specify a descending sort order.

Can you ORDER BY aggregate?

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.

Can we use ORDER BY for multiple columns?

In Excel, you can sort your table by one or more columns, by ascending or descending order, or do a custom sort.

How do I sort multiple columns in MySQL?

Summary. Use the ORDER BY clause to sort the result set by one or more columns. Use the ASC option to sort the result set in ascending order and the DESC option to sort the result set in descending order. The ORDER BY clause is evaluated after the FROM and SELECT clauses.


1 Answers

Suppose you have a table named 'Students'

enter image description here

Now you want to know the total marks scored by each student. So, type the following query

SELECT Name, S1, S2, SUM(S1+S2) AS TOTAL
FROM Students
GROUP BY Name, S1, S2
ORDER BY Total;

You will get the following result.

enter image description here

like image 169
Rakesh Anand Avatar answered Oct 14 '22 17:10

Rakesh Anand