Non ho i tuoi dati di esempio, ma ho appena ricreato lo scenario qui con una singola tabella: Dimostrazione
Potresti LEFT JOIN
i conteggi con generate_series()
e ottieni zero per il conteggio mancante di n
abbonamenti. Se non vuoi zeri, usa la seconda query.
Query1
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;
Query2
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;