如何使用“COUNT”和“GROUP BY”& “哪里”

时间:2014-09-13 18:53:42

标签: mysql sql count group-by

SELECT `loanac`.`id`, `loanac`.`area`
FROM loanac, loantrans
WHERE `loanac`.`lacc`=`loantrans`.`account`
GROUP BY `loanac`.`lacc`
HAVING SUM(IFNULL(`loantrans`.`out`,0)) > SUM(IFNULL(`loantrans`.`in`,0))

QUERY RESULT:

----------------------------------------
id      area
----------------------------------------
5       A
165     C
166     C
167     C
232     D
91      B

这个查询给了我所有的id&对于已经输入>的lacc的区域,此查询是OK&工作,我只需要从此查询中获取输出GROUP BY区域和COUNT个id。有人可以帮忙吗?

我想要的是

----------------------------------------
COUNT(id)      GROUP BY(area)
----------------------------------------
1               A
5               B
9               C
1               D

注意:条件不会改变 目标:想要在相同条件下查找/计算(loanac.area)分组的数量(loanac.area)

2 个答案:

答案 0 :(得分:0)

我想你想要这样的东西。将area添加到GROUP BY行,并使用COUNT(id)来获取交易次数。

SELECT count(`loanac`.`id`),
       SUM(IFNULL(`loantrans`.`out`,0)) AS transout,
       SUM(IFNULL(`loantrans`.`in`,0)) AS transin,
       `loanac`.`area`,
       `loanac`.`lacc`
FROM loanac, loantrans
WHERE `loanac`.`lacc`=`loantrans`.`account`
GROUP BY `loanac`.`lacc`,`loanac`.`area`
HAVING transout > transin

编辑:要提供您正在寻找的输出


SELECT count(loanac.id), `loanac`.`area`
FROM loanac, loantrans
WHERE `loanac`.`lacc`=`loantrans`.`account`
GROUP BY `loanac`.`lacc`,`loanac`.`area`
HAVING SUM(IFNULL(`loantrans`.`out`,0)) > SUM(IFNULL(`loantrans`.`in`,0))

答案 1 :(得分:0)

我认为这符合您的要求:

SELECT COUNT(id), area FROM
  (SELECT id, area FROM loanac
     JOIN loantrans ON loanac.lacc = loantrans.account
     GROUP BY loanac.lacc
     HAVING SUM(IFNULL(loantrans.out, 0)) > SUM(IFNULL(loantrans.in,0))) t
  GROUP BY area;

上面,我有一个loanac.area组,因为这就是原始示例的样子。如果您想按loanac.lacc进行分组,只需将上面的GROUP BY更改为GROUP BY loanac.lacc

编辑:在评论中链接的测试数据库中加载并运行查询会产生:

+-----------+------+
| COUNT(id) | area |
+-----------+------+
|        86 | A    |
|        81 | B    |
|        64 | C    |
|        66 | D    |
|        20 | E    |
|         3 | F    |
+-----------+------+