有这样一个表,数据是这样的
| id   | name |
+------+------+
|    1 | a    |
|    1 | b    |
|    1 | c    |
|    2 | d    |
|    2 | e    |
通过分组查询可以得到这样的结果
select count(id) from a group by id;
+-----------+
| count(id) |
+-----------+
|         3 |
|         2 |
+-----------+现在的要求是我想分组统计相同id的值出现过次数>2次的记录。
比如上面:
|    2 | d    |
|    2 | e    |这样记录应该舍去,如果是你,你会怎么写SQL语句?

解决方案 »

  1.   

    select * from 有这样一个表 a
    where 2<(select count(*) from 有这样一个表 where id=a.id)
      

  2.   

    select *
    from tb
    where id in (select id from tb group by id having count(*)>2)
      

  3.   

    select a.* from tt a inner join
    (select id from tt group by id having count(*)>2) b
    on a.id=b.id
      

  4.   

    select a.* from tt a inner join
    (select id from tt group by id having count(*)>2) b
    on a.id=b.id楼上的回复很好了。