选择仅按列分组,而不是聚合

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.

这篇关于选择仅按列分组,而不是聚合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

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

相关文档推荐

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代码排序)