1

The table looks like this

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

The OBJECT_ID value 910675 has two related OBJECT_ID values in RELATED_TO_OBJECT_ID. I would like to find the top 400 OBJECT_IDs having the most RELATED_TO_OBJECT_ID records and also where CLASS_ID = 7 and RELATION_TYPE_ID = 1.

Necreaux
  • 9,451
  • 7
  • 26
  • 43

2 Answers2

1

You need a query along these lines, I think:

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

The inner query creates a sorted table of OBJECT_IDs and the number of them that appear, then the outer query takes that result and limits it to the first 400 rows.

Note, I don't have an Oracle setup, but I referred to this previous question.

Ken Y-N
  • 14,644
  • 21
  • 71
  • 114
0

If you are on Oracle 12c, you could use the new Top-n row limiting feature.

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

If you want to include the duplicates, then add 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
Lalit Kumar B
  • 47,486
  • 13
  • 97
  • 124