选择总和,其中总和
我想根据最大+总和条件选择一些条目。
mytable
----------
id | col1 | col2
我想选择具有 col1 和 col1 之和的所有条目col2 大于或等于总和减去 X 的最大值。(不要问我为什么:))
到目前为止,我设法得到了总和 OK(以下别名为“总计”):
SELECT id,SUM(col1 + col2) AS total FROM mytable GROUP BY id;
我还设法得到了 MAX总和 OK(尽管有 ORDER BY/LIMIT 解决方法):
SELECT id,SUM(col + col) as total FROM mytable GROUP BY id ORDER BY total DESC LIMIT 1;
但是每次我尝试重新使用别名作为条件(例如 WHERE Total >= ...)时,我都会收到“未知列”错误< /strong>
任何事情都会非常感激
I want to select some entries based on a max+sum condition.
mytable
----------
id | col1 | col2
I want to select all entries that have the sum of col1 & col2 greater than or equal to the max of sum minus X. (don't ask me why :) )
So far I managed to get the sum OK (hereafter aliased as "total") with:
SELECT id,SUM(col1 + col2) AS total FROM mytable GROUP BY id;
I also managed to get the MAX of the sum OK (with a ORDER BY/LIMIT workaround though):
SELECT id,SUM(col + col) as total FROM mytable GROUP BY id ORDER BY total DESC LIMIT 1;
However everytime I try to re-use my alias as a condition (e.g. WHERE total >= ...) I get an "Unknown column" error
Anything would be greatly appreciated
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您对
SUM
有一些误解。SUM
是一个聚合函数,意味着它适用于许多记录,而不仅仅是一个。要计算每条记录两个字段的总和,您应该仅使用
+
运算符。You have some misconceptions about
SUM
.SUM
is an aggregating function, means it works on many records and not just one.To calculate the sum of two fields per record, you should use only the
+
operator.如果您使用 group by,则需要使用having 子句:
If you are using group by, you'll need to use a having clause: