仅当有超过2个相似行时才进行分组?

时间:2012-03-24 05:15:35

标签: mysql sql aggregate-functions

我想仅在有超过2个rwos匹配规则时才对项目进行分组。怎么办呢?

E.G :(按Col分组)

Col 
----
A
A
B
B
B

应该返回:

Col | count(*)
---------------
A     2
A     2
B     3

它只显示B一次,因为有超过3个结果。

1 个答案:

答案 0 :(得分:2)

由于MySQL没有COUNT OVER,你需要一个内联视图来获取计数小于3时的计数。然后它只是一个正常计数查询的联合

SELECT counts.col, 
       counts.k 
FROM   test 
       INNER JOIN (SELECT col, 
                          COUNT(col) k 
                   FROM   test 
                   GROUP  BY col
                   having count(col)  < 3 ) counts 
         ON test.col = counts.col 

UNION ALL 
SELECT col, 
       COUNT(col) k 
FROM   test 
GROUP  BY col 
HAVING COUNT(col) > 2 

See it working here