Select grouped by column only, not the aggregate

岁酱吖の 提交于 2020-01-16 06:57:09

问题


In a MySql select statement involving aggregation, is it possible to select just the grouped by column without the aggregate?

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
)

... 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?

Edit: if possible I would prefer to avoid using a join - the where clause is being passed onto another existing function on its own.

Apologies if this is a dupe - I did search, honest. I couldn't find an exact answer in the mass of SQL aggregate questions.


回答1:


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
)

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.




回答2:


WHERE idclient IN (...)

The stuff inside (...) is a subquery. Obviously it should only return one column, because you only need one column of data for the IN clause.

You can omit the total column by:

SELECT idclient
FROM payment
GROUP BY idclient
HAVING SUM(amount) > 100



回答3:


You could also try this one:

SELECT c.idclient, c.business_name
FROM payment p
  INNER JOIN client c ON c.idclient = p.idclient
GROUP BY c.idclient, c.business_name
HAVING SUM(p.amount) > 100

And, because the client.idclient column looks very much like a PK, you could probably even omit client.business_name from GROUP BY. So the final query would look like this:

SELECT c.idclient, c.business_name
FROM payment p
  INNER JOIN client c ON c.idclient = p.idclient
GROUP BY c.idclient
HAVING SUM(p.amount) > 100


来源:https://stackoverflow.com/questions/5494970/select-grouped-by-column-only-not-the-aggregate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!