如何在 MySQL 中按 SUM() 排序? [英] How to ORDER BY a SUM() in MySQL?

查看:124
本文介绍了如何在 MySQL 中按 SUM() 排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张表:ID 名称 c_counts f_counts"

I have a table: "ID name c_counts f_counts "

我想通过 sum(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;

推荐答案

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

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.

试试这个:

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

或者这个:

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

多种可能性!

这篇关于如何在 MySQL 中按 SUM() 排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆