计算sql中重复的组值

时间:2014-08-20 14:50:41

标签: sql sqlite count

我有一张表,其中包含具有唯一p_id的个人的重复记录,这些人是具有s_id的不同站点的成员。如何获得具有X个唯一p_id的网站数量?

所以目前我有

p_id  name   s_id
----  ----   ----
1     John   01
2     Alex   01
3     Ben    02
4     Mark   02
5     Colin  02
etc

我想使用SQL来生成这个表:

Site with 1 people: 0
Sites with 2 people: 1
Sites with 3 people: 3

我想过这样做:

select p_id, s_id, s_count from 
  (select p_id, s_id, count(*) as s_count from mytable group by s_id)

但我不认为这是正确的,可能有更好的方法 - 任何想法?

如果有人感到困惑 - 我正在寻找sql语句来获取计数,而不是其他任何事情。

1 个答案:

答案 0 :(得分:3)

首先,计算每个网站的人数:

SELECT s_id,
       COUNT(*) AS NumberOfPeople
FROM ATable
GROUP BY s_id

每个站点输出一行。

然后,再次分组,但是先前计算的计数列:

SELECT NumberOfPeople,
       COUNT(*) AS NumberOfSites
FROM (SELECT s_id,
             COUNT(*) AS NumberOfPeople
      FROM ATable
      GROUP BY s_id)
GROUP BY NumberOfPeople