MYSQL计数,分组依据和where子句

时间:2015-09-16 11:11:42

标签: mysql

这是有效的

SELECT COUNT(*) AS count ,transaction_id FROM loans_applicant  GROUP BY transaction_id

但是我想这样做

SELECT COUNT(*) AS count ,transaction_id FROM loans_applicant  GROUP BY transaction_id WHERE count > 4

我该怎么做?

3 个答案:

答案 0 :(得分:1)

这个条件应该进入HAVING条款,如下所示。而且,你已将WHERE置于错误的位置;它应该在FROM子句之后。

SELECT COUNT(*) AS count ,
transaction_id 
FROM loans_applicant  
GROUP BY transaction_id 
HAVING COUNT(*) > 4;

答案 1 :(得分:0)

按照以下顺序 -

where
group by
having
order by

通过这种方式,您的查询将是 -

SELECT COUNT(*) AS count ,transaction_id 
FROM loans_applicant 
GROUP BY transaction_id
having count > 4;

答案 2 :(得分:0)

你可以做两件事。
首先:使用HAVING子句。

  SELECT COUNT(*) AS count ,transaction_id FROM loans_applicant  GROUP BY transaction_id having count(*) > 4  

第二:使用子查询。

 SELECT count from (SELECT COUNT(*) AS count ,transaction_id FROM loans_applicant  GROUP BY transaction_id) where count > 4