No tengo sus datos de muestra, pero acabo de recrear el escenario aquí con una sola tabla: Demostración
Podrías LEFT JOIN
las cuentas con generate_series()
y obtenga ceros para el conteo faltante de n
membresías Si no quiere ceros, simplemente use la segunda consulta.
Consulta1
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;
Consulta2
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;