Top n distinct values of one column in Oracle

烂漫一生 提交于 2020-01-11 10:37:42

问题


I'm using a query where a part of it gets the top 3 of a certain column.

It creates a distinct subquery of the column, limited by 3 number of rows, and then filters those rows to the main query to do the top 3.

WITH subquery AS (
  SELECT col FROM (
    SELECT DISTINCT col
    FROM tbl
  ) WHERE ROWNUM <= 3
)

SELECT col
FROM tbl
WHERE tbl.col = subquery.col

So the original table is like this:

 col
-----
 a
 a
 a
 b
 b
 b
 c
 d
 d
 e
 f
 f
 f
 f

And the query returns the top 3 of the column (not the top 3 rows which would only be a):

 col
-----
 a
 a
 a
 b
 b
 b
 c

I'm trying to learn if there is a more correct way of doing this as the real query is big and duplicating its size with a subquery that looks almost the same just to get the top 3 is hard to work with and understand/modify.

Is there a better way to do the top first 3 distinct values of one column in Oracle?


回答1:


Yes, you can use dense_rank and avoid duplicated code:

select col 
  from (select col, dense_rank() over (order by col) rnk from tbl)
  where rnk <= 3

demo



来源:https://stackoverflow.com/questions/56852309/top-n-distinct-values-of-one-column-in-oracle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!