一尘不染

如何在MySQL中按SUM()排序?

mysql

我有一张桌子:“ ID名称c_counts f_counts”

我想按顺序排序所有记录,sum(c_counts+f_counts) 但这不起作用:

SELECT * FROM table ORDER BY sum(c_counts+f_counts) LIMIT 20;


阅读 1687

收藏
2020-05-17

共1个答案

一尘不染

别忘了,如果要混合使用分组(即SUM)字段和非分组字段,则需要对非分组字段之一进行GROUP BY。

尝试这个:

SELECT SUM(something) AS fieldname
FROM tablename
ORDER BY fieldname

或这个:

SELECT Field1, SUM(something) AS Field2
FROM tablename
GROUP BY Field1
ORDER BY Field2

而且,您始终可以执行以下派生查询:

SELECT
   f1, f2
FROM
    (
        SELECT SUM(x+y) as f1, foo as F2
        FROM tablename 
        GROUP BY f2
    ) as table1
ORDER BY 
    f1

许多可能性!

2020-05-17