Oracle SQL:计算给定条目的属性出现频率并选择出现次数最多的属性

Oracle SQL: Counting how often an attribute occurs for a given entry and choosing the attribute with the maximum number of occurs

我有一个 table,它有一个数字列和一个属性列,如下所示:

1.
+-----+-----+
| num | att |
-------------
|  1  |  a  | 
|  1  |  b  |
|  1  |  a  |
|  2  |  a  |
|  2  |  b  |
|  2  |  b  |
+------------

我想让数字唯一,属性是该数字最常出现的属性,就像这样(这是我感兴趣的最终产品):

2.
+-----+-----+
| num | att |
-------------
|  1  |  a  | 
|  2  |  b  |
+------------

我已经为此工作了一段时间,并设法为自己编写了一个查询,用于查找给定数字的某个属性出现的次数,如下所示:

3.
+-----+-----+-----+
| num | att |count|
------------------+
|  1  |  a  |  1  |
|  1  |  b  |  2  |
|  2  |  a  |  1  |
|  2  |  b  |  2  |
+-----------------+

但我想不出一种方法来仅 select 上面 table 中计数最高的那些行(当然对于每个数字)。

所以基本上我要问的是 table 3,我如何 select 只有每个数字计数最高的行(当然是描述提供一种方法的答案table 1 到 table 2 直接也可以作为答案:) )

您可以使用聚合和 window 函数:

select num, att
from (
    select num, att, row_number() over(partition by num order by count(*) desc, att) rn
    from mytable
    group by num, att
) t
where rn = 1

对于每个num,这带来了最频繁的att;如果有联系,则保留较小的 att

您可以使用分组依据和计数如下

select id, col, count(col) as count
from
df_b_sql
group by id, col

Oracle 有一个聚合函数可以执行此操作,stats_mode().:

select num, stats_mode(att)
from t
group by num;

在统计中,最常见的值称为 模式 -- 因此函数的名称。

Here 是一个 db<>fiddle.