PostgreSQL
 sql >> Datenbank >  >> RDS >> PostgreSQL

Postgres-Windows-Funktion mit aggregierter Gruppierung nach

Sie können Ihre Abfrage wie folgt ändern:

with cte1 as (
    SELECT email,
           lower(substring(u.email from position('@' in u.email)+1)) as domain
      FROM questions q
      JOIN identifiers i ON (q.owner_id = i.id)
      JOIN users u ON (u.identifier_id = i.id)
), cte2 as (
    select
        domain, email,
        count(*) as questions_per_email,
        first_value(email) over (partition by domain order by count(*) desc) as top_user
    from cte1
    group by email, domain
)
select domain, top_user, sum(questions_per_email) as questions_per_domain
from cte2
group by domain, top_user

SQL-Fiddle-Demo