SQL按一个条件对N条记录进行排序,并按另一条条件对N条记录进行排序

时间:2018-12-27 17:02:24

标签: sql loops ranking

在我的表格中,我有4列ID,分别键入InitialRanking和FinalRanking。根据某些条件,我设法将InitialRanking应用于记录(1-20)。现在,我需要通过确定类型1的前7位,然后是

来应用FinalRanking

enter image description here

类型2的前3个。然后,我需要重复上述操作,直到所有记录都具有FinalRanking。我的目标是在所附图像的最后一栏中实现输出。

7和3会随时间而变化,但就本示例而言,我们假设它们是固定的。

2 个答案:

答案 0 :(得分:0)

您可以尝试这样

       SELECT * FROM(

       ( SELECT ID,DISTINCT TYPE,

          CASE  WHEN TYPE=1 THEN
          ( SELECT TOP 7 INITIALRANK, FINALRANK
            from table where type=1)

         ELSE

          (  SELECT TOP 3 INITIALRANK, FINALRANK
            from table where type=2)

       END CASE 

       FROM TABLE WHERE TYPE IN (1,2)

           )

              UNION

            (    SELECT ID,TYPE,
               INITIALRANK, FINALRANK
                from table where type not in (1,2))

                )
         )

答案 1 :(得分:0)

一种简单(或简单化)的最终排名方法是:

row_number() over (partition by type order by initrank) +
case type
     when 1 then (ceil((row_number() over (partition by type order by initrank))/7)-1)*(10-7)
     when 2 then (ceil((row_number() over (partition by type order by initrank))/3)-1)*(10-3)+7
end FinalRank

这可以概括为两个以上的组,例如具有大小为7、3和2的三个组,模式大小为7 + 3 + 2 = 12,一般形式为PartitionedRowNum +(Ceil(PartitionedRowNum / GroupSize)-1 )*(PaternSize-GroupSize)+ Offset,其中,偏移量是上述组大小的总和:

row_number() over (partition by type order by initrank) +
case type
     when 1 then (ceil((row_number() over (partition by type order by initrank))/7)-1)*(12-7)
     when 2 then (ceil((row_number() over (partition by type order by initrank))/3)-1)*(12-3)+7
     when 3 then (ceil((row_number() over (partition by type order by initrank))/2)-1)*(12-2)+7+3
end FinalRank
相关问题