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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.