SQL按"重量"排序记录

Ken*_*enD 5 sql t-sql sql-server-2008

我们有一个系统,通过表中的"优先级"数字处理记录.我们通过表的内容来定义优先级,例如

UPDATE table
SET priority=3
WHERE processed IS NULL

UPDATE table
SET priority=2
WHERE balance>50

UPDATE table
SET priority=1
WHERE value='blah'
Run Code Online (Sandbox Code Playgroud)

(请忽略优先级之间可能存在'重叠'的事实:)

这样可以正常工作 - 表按优先级顺序处理,因此首先处理"value"列为"blah"的所有行.

我已经被赋予了添加选项以通过可定义的"权重"来订购记录的任务.例如,我们希望50%的处理优先级为1,优先级为25%,优先级为25%,优先级为25%.因此,根据上述情况,在每100条记录中,其中50条将是"值"为"blah"的记录. ",其中25个将是"平衡"大于50等的地方.

我正在试图弄清楚如何做到这一点:"优先级"的某种加权递增值似乎是最好的方法,但我无法理解如何对此进行编码.有人可以帮忙吗?

编辑:道歉,应该说:这是在MSSQL 2008上运行

Thi*_*Jet 5

一般的想法是将任务收集到桶中,划分为整数的边界:

select
  task_id
from (  
  select 
    task_id, 
    ((task_priority_order - 1) / task_priority_density) as task_processing_order
  from (
    select
      t.task_id                                            as task_id, 
      t.priority                                           as task_priority, 
      row_number() 
        over (partition by t.priority order by t.priority) as task_priority_order,
      case
        when t.priority = 3 then 50
        when t.priority = 2 then 25
        when t.priority = 1 then 25
      end                                                  as task_priority_density
    from
      table t
  )
)
order by task_processing_order
Run Code Online (Sandbox Code Playgroud)

在从0.0到0的调和中.(9)我们得到了100条记录,这些记录是从优先级为3的前50条记录,优先级为2的前25条记录和优先级为1的前25条记录构建的.

从1.0到1的下一个调和(9)代表下一桶记录.

如果没有具有某些优先级值的任务,则剩余的任务将以相同的比率放入存储桶中.例如,如果没有足够的优先级为3的任务,则剩余的任务将以50/50的比例排列.

task_id - 用于任务识别的一些代理键.

PS抱歉,我现在无法测试此查询,因此任何语法更正都非常感激.

更新:根据注释更正查询语法.