我正在嘗試寫一個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;