简体   繁体   English

对行进行分组和计数,然后在有条件的情况下使用它们

[英]Group and count rows and then use them in condition

I have an query like: 我有一个查询,如:

SELECT * FROM account AS a 
LEFT JOIN (SELECT SUM(bill.amount) total, bill.accountId FROM bill GROUP BY bill.accountId) b ON a.id = b.accountId
WHERE a.partner_id = 1 OR a.partner_id = 2

How can I check, how many groups in "bill" has the same a.partner_id? 如何检查“帐单”中有多少个组具有相同的a.partner_id? For example: 3 groups has partner_id = 1, 2 groups has partner_id = 2. 例如:3个群组的partner_id = 1,两个群组的partner_id = 2。

And later include to left join only groups, if more than 2 groups have the same partner_id. 如果两个以上的组具有相同的partner_id,则以后仅包括左联接组。

If I understand correctly, you just want an aggregation on top of your query: 如果我理解正确,那么您只想在查询之上进行汇总:

SELECT a.partner_id, count(*) as cnt, sum(total) as total
FROM account a LEFT JOIN
     (SELECT SUM(b.amount) as total, b.accountId
      FROM bill b
      GROUP BY b.accountId
     ) b
     ON a.id = b.accountId
GROUP BY a.partner_id;

You should be able to use the "HAVING" clause. 您应该可以使用“ HAVING”子句。 Below is an example from the following link: https://dev.mysql.com/doc/refman/5.0/en/group-by-handling.html 下面是来自以下链接的示例: https : //dev.mysql.com/doc/refman/5.0/en/group-by-handling.html

SELECT name, COUNT(name) AS c FROM orders
  GROUP BY name
  HAVING c = 1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM