0

我有一个具有不同集群 ID 的表

ID  
1  
1  
2  
2      
2    
3  
3  
3  
3  
4  
4  

我想显示集群的大小以及该集群中的集群数量。

例如对于上表预期输出:

Cluster Size | No of Clusters (with that size)
2            | 2  
3            | 1  
4            | 1  

我写了一个查询,它将给我指定的集群大小。

Select COUNT(*) from  
(SELECT  ID, COUNT(ID) as cnt  
  FROM [Table] group by ID having COUNT(*) =3) as TC;

在上面的示例中,我将得到“1”作为上表的结果。

但是,我想要一个查询,它会给我所有的集群及其各自的大小。

4

3 回答 3

2
SELECT c AS ClusterSize, COUNT(*) AS NumOfClusters
FROM
(
    SELECT COUNT(*) AS c, ID
    FROM @table
    GROUP BY ID

)A
GROUP BY c
于 2013-03-14T17:20:29.907 回答
2
select [Cluster Size], Count(*) as [No of Clusters]
from (
    select count(*) as [Cluster Size]
    from Table1
    group by ID
) a
group by [Cluster Size]

SQL 小提琴示例

输出:

| CLUSTER SIZE | NO OF CLUSTERS |
---------------------------------
|            2 |              2 |
|            3 |              1 |
|            4 |              1 |
于 2013-03-14T17:22:23.857 回答
0

如果我了解您的要求,则此查询应该可以完成:

SELECT cl.size, COUNT(cl.size)
FROM
(SELECT id, COUNT(id) [Size] FROM Table1 GROUP BY id) cl
GROUP BY cl.size

这是 SQL Fiddle 的链接:http ://sqlfiddle.com/#!3/56de3/7

于 2013-03-14T17:17:40.693 回答