表格如下所示
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
。
答案 0 :(得分: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。
答案 1 :(得分:0)
如果您使用的是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