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

How to ORDER BY a SUM() in MySQL?(如何在 MySQL 中按 SUM() 排序?)
本文介绍了如何在 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() 排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)