选择总和,其中总和

发布于 2024-09-13 01:15:49 字数 564 浏览 5 评论 0原文

我想根据最大+总和条件选择一些条目。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浅忆 2024-09-20 01:15:49

您对 SUM 有一些误解。 SUM 是一个聚合函数,意味着它适用于许多记录,而不仅仅是一个。
要计算每条记录两个字段的总和,您应该仅使用 + 运算符。

SELECT id, col1+col2 AS 'total'
FROM T1
WHERE
(col1+col2+x) >=(SELECT MAX(col1+col2) from T1)

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.

SELECT id, col1+col2 AS 'total'
FROM T1
WHERE
(col1+col2+x) >=(SELECT MAX(col1+col2) from T1)
唯憾梦倾城 2024-09-20 01:15:49

如果您使用 group by,则需要使用having 子句:

SELECT id,SUM(col1+col2) as total FROM mytable GROUP BY id ORDER BY total HAVING total >= x

If you are using group by, you'll need to use a having clause:

SELECT id,SUM(col1+col2) as total FROM mytable GROUP BY id ORDER BY total HAVING total >= x
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文