如何基于多列权重明智排序获得结果

How to get result based on multiple column weightage wise sorting

我的问题很有意思,需要这里所有sql高手的帮助。

我有以下输入表单来接受用户的输入:

用户将为 c1、c2 等输入值、方差和权重

结果table如下

我需要根据以下条件从结果 table 中检索数据:

  1. 用户 c1 输入的值应与 table 的 c1 列中的给定方差百分比匹配。例如,输入的值是 15000,% 是 10,所以在 table.

  2. 中匹配应该是 10% +-
  3. 结果应按照用户为每一列指定的权重排序。最大权重为 5。 例如。即使 C1 值完全匹配并且 c2 值与方差接近匹配,如果 c2 的权重较高,则 c2 行应该在顶部。

我尝试了以下查询:

DECLARE @c1 int; set @c1 = 15000;
DECLARE @c2 int; set @c2 = 4;
DECLARE @c3 int; set @c3 = 570;
DECLARE @c4 int; set @c4 = 2000;
DECLARE @c5 int; set @c5 = 450;
select results.*, ((((@c1 - c1val) * 100 / @c1 ) * 6-1) + (((@c2 - c2val) * 100 / @c2) * 6 - 1) + (((@c3 - c3val) * 100 / @c3) * 6-5)+ (((@c4 - c4val) * 100 / @c4) * 6-3)+ (((@c5 - c5val) * 100 / @c5) * 6-3)) AS relevance 
from results
where (c1val <= @c1 - (@c1 * 10 /100) or c1val > = @c1 +  (@c1 * 10 /100)) or 
      (c2val <= @c2 - (@c2 * 25 /100) or c2val > = @c2 + (@c2 * 25 /100)) or
      (c3val <= @c3 - (@c3 * 20 /100) or c3val > = @c3 + (@c3 * 20 /100)) or
      (c4val <= @c4 - (@c4 * 10 /100) or c4val > = @c4 + (@c4 * 10 /100)) or
      (c5val <= @c5 - (@c5 * 15 /100) or c5val > = @c5 + (@c5 * 15 /100))

order by relevance desc

但它无法正常工作。

首先你需要十进制运算,声明@c1 等十进制。否则所有表达式都转换为 int。接下来我猜你需要 abs(@c1 - c1val) 等相关表达式。我的猜测是相关性与偏差成反比。

尝试

DECLARE @c1 decimal(7,2) = 15000
      , @var1 decimal(4,3) = 10./100;
DECLARE @d1 decimal(7,3) = @c1 * @var1
      , @w1 int = 1;
...
select * 
from(
    select results.*
        , (100 - abs(@c1 - c1val) * 100 / @c1)  * (6 - @w1) 
        +  ...  AS relevance 
    from results
    where (c1val between @c1 - @d1 and  @c1 + @d1)
       AND  ...
) t
order by relevance desc

相关性可能需要某种调整才能在权重和偏差之间取得适当的平衡。

以下查询工作完美:

ALTER PROCEDURE [dbo].[GetResult] 
    @c1 as decimal(7,2), @c2 as decimal(7,2), @c3 as decimal(7,2), @c4 as decimal(7,2), @c5 as decimal(7,2), 
    @v1 as decimal, @v2 as decimal, @v3 as decimal, @v4 as decimal, @v5 as decimal, 
    @w1 as int, @w2 as int, @w3 as int, @w4 as int, @w5 as int
AS
BEGIN

DECLARE @var1 decimal(4,3) = @v1/100;
DECLARE @d1 decimal(7,3) = @c1 * @var1

DECLARE @var2 decimal(4,3) = @v2/100;
DECLARE @d2 decimal(7,3) = @c2 * @var2;

DECLARE @var3 decimal(4,3) = @v3/100;
DECLARE @d3 decimal(7,3) = @c3 * @var3

DECLARE @var4 decimal(4,3) = @v4/100;
DECLARE @d4 decimal(7,3) = @c4 * @var4

DECLARE @var5 decimal(4,3) = @v5/100;
DECLARE @d5 decimal(7,3) = @c5 * @var5

select * 
from(
    select results.*
        ,   (abs(@c1 - c1val) / @c1 * @w1 +
            abs(@c2 - c2val) / @c2 * @w2 +
            abs(@c3 - c1val) / @c3 * @w3 +
            abs(@c4 - c1val) / @c4 * @w4 +
            abs(@c5 - c1val) / @c5 * @w5 / 5)
            AS relevance 
    from results
    where (c1val between @c1 - @d1 and  @c1 + @d1) or
          (c2val between @c2 - @d2 and  @c2 + @d2) or
          (c3val between @c3 - @d3 and  @c3 + @d3) or
          (c4val between @c4 - @d4 and  @c4 + @d4) or
          (c5val between @c5 - @d5 and  @c5 + @d5)
) t
order by relevance
END