2015-06-05 73 views
1

的表看起來像這樣查找具有TOP 400行最關係

RELATION_ID OBJECT_ID RELATED_TO_OBJECT_ID CLASS_ID RELATION_TYPE_ID 
7966561  910675    69305    7    1 
7966562  910675    439104    7    1 

的OBJECT_ID值910675有RELATED_TO_OBJECT_ID兩個相關OBJECT_ID值。我想找到具有最多RELATED_TO_OBJECT_ID記錄的前400個OBJECT_ID,也是where CLASS_ID = 7 and RELATION_TYPE_ID = 1

+1

請修改問題並在問題(作爲文本列表)和所需輸出中提供*相關*樣本數據。 –

+0

請注意,'SELECT TOP 400'是[MySQL專用](http://stackoverflow.com/a/9150494/1270789)。請參閱下面的Oracle版本的答案。 –

+1

@ KenY-N從12c開始,Oracle支持top-n行限制功能。 –

回答

1

你需要沿着這些路線的查詢時,我想:

SELECT * FROM (
    SELECT OBJECT_ID, COUNT(*) as objectcount 
    FROM table 
    WHERE CLASS_ID = 7 AND RELATION_TYPE_ID = 1 
    GROUP BY OBJECT_ID ORDER BY objectcount DESC) 
WHERE ROWNUM <= 400 

內的查詢創建object_id中排序表和出現,再查詢外層採用的是結果,它限制了它們的數量前400排。

請注意,我沒有Oracle安裝程序,但我提到了this previous question

+0

我想你打算在最後的where子句中使用<= – karina

+0

謝謝,[你的確是正確的](http://www.adp-gmbh.ch/ora/sql/examples/first_rows.html)! –

+1

@ KenY-N你需要通過desc命令。 –

0

如果您使用的是Oracle 12c,則可以使用新的前n行限制功能。

SELECT OBJECT_ID, 
    COUNT(*) cnt 
FROM table_name 
WHERE CLASS_ID  = 7 
AND RELATION_TYPE_ID = 1 
GROUP BY OBJECT_ID 
ORDER BY cnt DESC 
FETCH FIRST 400 ROWS ONLY 

如果你想包括重複,再加入WITH TIES

SELECT OBJECT_ID, 
    COUNT(*) cnt 
FROM table_name 
WHERE CLASS_ID  = 7 
AND RELATION_TYPE_ID = 1 
GROUP BY OBJECT_ID 
ORDER BY cnt DESC 
FETCH FIRST 400 ROWS WITH TIES