MYSQL Order By Sum of Columns

情到浓时终转凉″ 提交于 2019-12-10 03:39:53

问题


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!


回答1:


Why not try before concluding it doesn't work? In point of fact, it does.




回答2:


Suppose you have a table named 'Students'

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.




回答3:


I think you should be able to do

SELECT *, col1+col2 as mysum ORDER BY mysum

Which is essentially the same as you already have




回答4:


The query you wrote should work just fine, you can have any expression in the ORDER BY clause.



来源:https://stackoverflow.com/questions/3059138/mysql-order-by-sum-of-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!