我正在尝试编写一个SQL查询,以找到众数,即出现次数比其他元素多的元素。 例如:
2,2,1,1---->在这里,输出应该为空(1和2都出现了两次) 3,3,3----->在这里,输出也应该为空(没有第二个元素) 3,3,1----->在这里,输出应该是3。(3的出现次数大于1的出现次数)
这是用于找到它的3个条件。我该如何实现它?
P粉1627736262023-09-13 00:50:40
您可以计算值的数量,找出频率最高的值,并且还可以根据值的数量进行筛选:
select x.* from (select val, count(*) as cnt, row_number() over (order by count(*) desc ) as seqnum, count(*) over () as num_vals count(*) over (partition by count(*)) as cnt_cnt from table group by val ) x where cnt_cnt = 1 and seqnum = 1 and num_vals > 1;
实际上,您可以使用having
子句和order by
来实现:
select val from (select val, count(*) as cnt, count(*) over () as num_values from table group by val ) v where num_values > 1 order by cnt desc;