Sql 如何按关系计数对结果进行分组
给定表、Sql 如何按关系计数对结果进行分组,sql,postgresql,Sql,Postgresql,给定表、Profiles和Memberships如果一个概要文件有许多成员身份,如何根据成员身份的数量查询概要文件 例如,我想获得具有2个成员资格的配置文件的数量。我可以通过以下方式获得每个成员的配置文件数: SELECT "memberships"."profile_id", COUNT("profiles"."id") AS "membership_count" FROM "profiles" INNER JOIN "memberships" on "profiles"."id" = "me
Profiles
和Memberships
如果一个概要文件有许多成员身份,如何根据成员身份的数量查询概要文件
例如,我想获得具有2个成员资格的配置文件的数量。我可以通过以下方式获得每个成员的配置文件数:
SELECT "memberships"."profile_id", COUNT("profiles"."id") AS "membership_count"
FROM "profiles"
INNER JOIN "memberships" on "profiles"."id" = "memberships"."profile_id"
GROUP BY "memberships"."profile_id"
返回的结果如下
profile_id | membership_count
_____________________________
1 2
2 5
3 2
...
但是如何对计数进行分组和求和,以使查询返回如下结果:
n | profiles_with_n_memberships
_____________________________
1 36
2 28
3 29
...
甚至只是查询一个将返回的n
值
profiles_with_2_memberships
___________________________
28
我没有您的示例数据,但我只是在这里用一个表重新创建了场景: 您可以使用
generate_series()
左键联接计数,并为n
成员身份的缺失计数获取零。如果不需要零,只需使用第二个查询
问题1
问题2
WITH c
AS (
SELECT profile_id
,count(*) ct
FROM Table1
GROUP BY profile_id
)
,m
AS (
SELECT MAX(ct) AS max_ct
FROM c
)
SELECT n
,COUNT(c.profile_id)
FROM m
CROSS JOIN generate_series(1, m.max_ct) AS i(n)
LEFT JOIN c ON c.ct = i.n
GROUP BY n
ORDER BY n;
WITH c
AS (
SELECT profile_id
,count(*) ct
FROM Table1
GROUP BY profile_id
)
SELECT ct
,COUNT(*)
FROM c
GROUP BY ct
ORDER BY ct;