将TOP 3放在单独的列中?

时间:2019-07-30 13:56:02

标签: sql sql-server sql-server-2008

我们说有一个列为animals的表:

-- animal --
   dog
   dog
   dog
   giraffe
   cat
   cat
   mouse
   mouse
   elephant

根据出现次数最多的TOP 3动物创建结果集的最佳方法是什么?它有3个单独的列,每个动物1个列。

结果集:

-- animal 1 -- animal 2 -- animal 3 --
   dog         cat         mouse

1 个答案:

答案 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