简体   繁体   English

在SQL查询中计算不同行的条件

[英]Condition for counting distinct rows in an SQL query

I have a table in a MySQL database with an ID column. 我在MySQL数据库中有一个带有ID列的表。 This is not a key of the table and several rows can have the same ID. 这不是表的键,几行可以具有相同的ID。

I don't really know SQL but I already figured out how to obtain the number of distinct IDs: 我并不真正了解SQL,但是我已经想出了如何获取不同ID的数量:

SELECT COUNT(DISTINCT ID) FROM mytable;

Now I want to count only those IDs which appear more than 2 times in the table. 现在,我只想统计表中出现两次以上的ID。

So if the ID column contains the values 因此,如果ID列包含值

 3 4 4 5 5 5 6 7 7 7

the query should return 2. 查询应返回2。

I have no idea how to do this. 我不知道该怎么做。 I hope someone can help me! 我希望有一个人可以帮助我!

Btw, my table contains a huge number of rows. 顺便说一句,我的表包含大量的行。 So if there are several possibilities I would also be happy to know which solution is the most efficient. 因此,如果有几种可能性,我也很高兴知道哪种解决方案最有效。

Try this: 尝试这个:

SELECT COUNT(ID) FROM (
    SELECT ID FROM mytable
    GROUP BY ID
    HAVING COUNT(ID) > 2) p
SELECT 
      COUNT(ids)
FROM 
      (SELECT 
           COUNT(ID)AS ids 
       FROM 
           mytable 
       GROUP BY 
           ID
       HAVING 
           ids>2
       )AS tbl1
select count(*) from 
    (select count(id) as cnt,id from mytable group by id) da 
where da.cnt>2

The inner query will give you how many elements does each id have. 内部查询将为您提供每个ID有多少个元素。 And the outer query will filter this. 外部查询将对此进行过滤。

Updated : 更新 :

SELECT count(ID) 
FROM (
SELECT ID FROM mytable
GROUP BY ID
HAVING count(ID) > 2
) p

should do what you need 应该做你需要的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM