Reputation: 31
I am using a postgresql setup and I have a table something like this:
sec_id prod_id
1 789
1 908
1 678
13 789
13 123
13 908
15 789
What I want to be able to is determine the overlap (common prod_ids) within the sec_id's. That is, I want to be able output something similar to:
sec_id1 sec_id2 overlap
1 13 2
1 15 1
13 1 2
13 15 1
15 1 1
15 13 1
I don't have very much experience with this and would appreciate any assistance.
Upvotes: 3
Views: 147
Reputation: 56049
I am used to MySQL so you may need to adjust the syntax slightly for postgres:
SELECT a.sec_id AS sec_id1, b.sec_id AS sec_id2, COUNT(*) AS overlap
FROM tblname AS a JOIN tblname AS b
WHERE a.prod_id = b.prod_id AND a.sec_id != b.sec_id
GROUP BY a.sec_id, b.sec_id
Probably, this would work in PostgreSQL (as well as in MySQL):
SELECT a.sec_id AS sec_id1, b.sec_id AS sec_id2, COUNT(*) AS overlap
FROM tblname AS a JOIN tblname AS b ON a.prod_id = b.prod_id
WHERE a.sec_id != b.sec_id
GROUP BY a.sec_id, b.sec_id
Upvotes: 2