ORACLE SQL:如何显示已排序表中列内容的出现次数?

时间:2015-06-08 10:12:54

标签: sql oracle

我想知道如何在排序表中显示列内容的出现次数

这是我的表REF内容,有两列:

POSITION| MYVAL
---------------
   1    | U
   2    | U
   3    | B
   4    | R
   5    | R
   6    | R
   7    | C

我想有这样的结果表(引入一个NO_OCCURENCE列,显示MYVAL内容的出现次数):

  POSITION | NO_OCCURENCE| MYVAL
  --------------------------------
     1     |     1       |   U
     2     |     2       |   U
     3     |     1       |   B
     4     |     1       |   R
     5     |     2       |   R
     6     |     3       |   R
     7     |     1       |   C

我如何在ORACLE SQL中执行此操作?

此致

2 个答案:

答案 0 :(得分:0)

您可以使用窗口功能:

select position,
       row_number() over (partition by myval order by position) as no_occurence, 
       myval
from the_table
order by position, myval;

答案 1 :(得分:0)

使用排名功能。请参阅RANK, DENSE_RANK, FIRST and LAST Analytic Functions

SELECT POSITION, 
       DENSE_RANK() OVER (PARTITION BY MYVAL ORDER BY POSITION ASC) AS NO_OCCURENCE, 
       MYVAL
FROM Table