2011-11-03 132 views
3

我使用PostgreSQL的設置,我有一個表是這樣的:PostgreSQL的查詢

sec_id  prod_id 
1   789 
1   908 
1   678 
13   789 
13   123 
13   908 
15   789 

我希望能夠爲確定sec_id的內重疊(普通PROD_IDS)。也就是說,我希望能夠輸出類似於:

sec_id1 sec_id2 overlap 
1   13   2  
1   15   1  
13   1   2  
13   15   1 
15   1   1 
15   13   1  

我對此沒有太多經驗,並希望得到任何幫助。

回答

2

我用MySQL的,所以你可能需要稍微調整一下語法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 

也許,這將在PostgreSQL的工作(以及在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 
+0

謝謝你這麼多。我衷心感謝幫助。 – user1028475