How to ORDER BY a SUM() in MySQL?

后端 未结 5 816
暗喜
暗喜 2020-11-27 19:12

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

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-27 19:20

    The problem I see here is that "sum" is an aggregate function.

    first, you need to fix the query itself.

    Select sum(c_counts + f_counts) total, [column to group sums by]
    from table
    group by [column to group sums by]
    

    then, you can sort it:

    Select *
    from (query above) a
    order by total
    

    EDIT: But see post by Virat. Perhaps what you want is not the sum of your total fields over a group, but just the sum of those fields for each record. In that case, Virat has the right solution.

提交回复
热议问题