Note that there are some explanatory texts on larger screens.

plurals
  1. POEfficient SQL to calculate # of shared affiliations
    primarykey
    data
    text
    <p>So I have </p> <ol> <li>a table that stores asymmetrical connections between two persons (like a Twitter follow; <em>not</em> like a Facebook friend) and </li> <li>a table that stores a person's affiliations to various groups</li> </ol> <p>My task is to find, for each asymmetrical relationship, the number of affiliations shared between the "from person" and the "to person".</p> <p>I made this brute force solution, but I'm wondering if brighter minds could come up with something more efficient.</p> <pre><code>select frm01.from_person_id, frm01.to_person_id, count(*) num_affl from ( select lnk.from_person_id, lnk.to_person_id, ga.grp_id from_grp_id from links lnk left outer join grp_affl ga on lnk.from_person_id = ga.person_id group by lnk.from_person_id, lnk.to_person_id, grp_id ) frm01 inner join ( select lnk.from_person_id, lnk.to_person_id, ga.grp_id to_grp_id from links lnk left outer join grp_affl ga on lnk.to_person_id = ga.person_id group by lnk.from_person_id, lnk.to_person_id, grp_id ) to01 on ( frm01.from_person_id = to01.from_person_id and frm01.to_person_id = to01.to_person_id and frm01.from_grp_id = to01.to_grp_id ) group by frm01.from_person_id, frm01.to_person_id; </code></pre> <p>Using ANSI SQL on Netezza (which doesn't allow correlated subqueries).</p> <p>TIA!</p> <p>Edited to add table schema:</p> <pre><code>table lnk: from_person_id to_person_id 1 4 2 5 3 6 4 2 5 3 table grp_affl: person_id grp_id 1 A 1 B 1 C 2 A 3 B 4 C 5 A 5 B 5 C 6 A expected output: from_person_id to_person_id num_affl 1 4 1 2 5 1 3 6 0 4 2 0 5 3 1 </code></pre> <p>Persons 1 &amp; 4 have 1 affiliation in common (C), 2 &amp; 5 have A in common, 5 &amp; 3 have B in common. 3 &amp; 6 have nothing in common. Likewise 4 &amp; 2.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload