如何在MySQL中按SUM()排序? [英] How to ORDER BY a SUM() in MySQL?
本文介绍了如何在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)字段和非分组字段,则需要对非分组字段之一进行分组字段.
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屋!
查看全文