1
votes

I'm stuck in loop.

I have a postgres database and i have to filter the top-5, unique co-author pairs by number of jointly published papers.

I want to return pairs of author names and paper count

SQL Schema

What i have so far:

select persons.name as person, count(papers.pkey) as amount 
from persons 
  inner join authpapers on authpapers.akey = persons.akey 
  inner join papers on authpapers.pkey = papers.pkey  
group by persons.name 
order by amount desc limit 5;

As a result i get the first 5 authors ba name and paper count but i want papers where an author had a co author.

1
If GMB's answer solved your problem (i assume that's the case because of your comment) you can affirm that by accepting it. - Tov Aqulic

1 Answers

1
votes

You can self-join the persons table to generate authors combinations, then bring each person's papers by joining authpapers once per user, and finally filter on matching papers. The final step is aggregation and sorting:

select p1.name as person1, p2.name person2, count(*) as amount
from persons p1
inner join persons p2 on p2.akey > p1.akey
inner join authpapers ap1 on ap1.akey = p1.akey 
inner join authpapers ap2 on ap2.akey = p2.akey 
where ap1.pkey = ap2.pkey
group by p1.akey, p2.akey
order by amount desc limit 5;

Note that you don't need the papers table to get the results that you want.