MySQL GROUP BY:仅包含具有特定列数的行

时间:2015-02-23 20:02:56

标签: mysql

我想创建一个查询,该查询计算包含A和B相同值的行数,但仅当任何给定A的B出现时> 10.换句话说,如果我的表中有11行如下:


| id | A | B | ... |

| 1  | a | a | ... |

| 2  | a | a | ... |

| 3  | a | a | ... |

| 4  | a | a | ... |

| 5  | a | a | ... |

| 6  | a | a | ... |

| 7  | a | a | ... |

| 8  | a | a | ... |

| 9  | a | a | ... |

| 10 | a | a | ... |

| 11 | a | b | ... |

使用以下查询:

从foos组中选择A,B,计数(B)由A,B按(?)顺序由计数(B)desc选择;

我希望以下内容返回:

| a | a | 10 |

更新/编辑:我需要在这里查看另外一个条件;对于上面给出的查询,我只想返回行,在GROUP_BY A, B的情况下,A出现在10个以上的返回行中。例如:

| 1  | a | a |
| 2  | a | b |
| 3  | a | c |
| 4  | a | d |
| 5  | a | e |
| 6  | a | f |
| 7  | a | g |
| 8  | a | h |
| 9  | a | i |
| 10 | a | j |
| 11 | a | k |

3 个答案:

答案 0 :(得分:1)

只需在having子句中添加条件。

select A, B, count(B)
from foos
group by A, B 
having count(B) > 10
order by count(B) desc;

<强>解释

此查询将沿A和B相同的记录计数获取A和B.如果计数大于10,则仅显示那些结果。

HAVING子句已添加到SQL,因为WHERE子句不能与聚合函数一起使用。

修改

如果要按A和B分组,则它不适用于更新的表数据。在这种情况下,你必须这样做,

select A, count(B)
from foos
group by A
having count(B) > 10
order by count(B) desc

答案 1 :(得分:1)

试试这个:

select A, B, count(B) as count
from foos 
group by A, B 
having (Count>10)
order by count(B) desc;

答案 2 :(得分:-2)

select A, B, count(B)
from foos
where count(B) > 10
group by A
order by count(B) desc;