Select grouped by column only, not the aggregate(选择仅按列分组,而不是聚合)
问题描述
在涉及聚合的 MySql 选择语句中,是否可以选择仅按列分组而不聚合?
In a MySql select statement involving aggregation, is it possible to select just the grouped by column without the aggregate?
基本上我想根据基于聚合的条件在子查询中选择 ID,在这种情况下是向客户支付的总金额:
Basically I want to select IDs in subquery according to a criteria based on an aggregate, in this case the total payments to a client:
select idclient, business_name from client where idclient in
(
select idclient, sum(amount) as total
from payment
group by idclient
having total > 100
)
... 但这失败并出现错误 Operand should contain 1 column(s) 因为子查询同时选择了 id(我想要的)和总数(我没有选择).我可以以任何方式从子查询结果中排除 total 吗?
... but this fails with error Operand should contain 1 column(s) because the subquery selects both the id (which I want) and the total (which I don't). Can I exclude total from the subquery result in any way?
如果可能的话,我宁愿避免使用连接 - where 子句被单独传递给另一个现有函数.
if possible I would prefer to avoid using a join - the where clause is being passed onto another existing function on its own.
抱歉,如果这是一个骗局 - 老实说,我确实搜索过.我在大量 SQL 聚合问题中找不到确切答案.
推荐答案
你的查询应该是这样的:
Your query should be like this:
select idclient, business_name from client where idclient in
(
select idclient
from payment
group by idclient
having sum(amount) > 100
)
您需要将聚合函数放在有子句中,在子查询中您需要选择与 where 子句中相同的列数.
You need to put aggregate function in having clause and in sub query you need to select # of columns same as in your where clause.
这篇关于选择仅按列分组,而不是聚合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:选择仅按列分组,而不是聚合
基础教程推荐
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- 带更新的 sqlite CTE 2022-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
