我们说有一个列为animals
的表:
-- animal --
dog
dog
dog
giraffe
cat
cat
mouse
mouse
elephant
根据出现次数最多的TOP 3动物创建结果集的最佳方法是什么?它有3个单独的列,每个动物1个列。
结果集:
-- animal 1 -- animal 2 -- animal 3 --
dog cat mouse
答案 0 :(得分:3)
您可以使用条件聚合:
select max(case when seqnum = 1 then animal end) as animal_1,
max(case when seqnum = 2 then animal end) as animal_2,
max(case when seqnum = 3 then animal end) as animal_3
from (select animal, count(*) as cnt, row_number() over (order by count(*) desc) as seqnum
from t
group by animal
) a