如何根据某些条件将 运行 值分配给行

How to assign a running value to a row depending on some conditions

我试图根据某些条件为我的行提供一定数量的点,但我不知道如何写。

对于给定的 Id、FormatCode 和 Price,我想给值 1。 对于后续行,对于相同的Id和Price,如果FormatCode是具有相同Id和price的前一行的倍数,我想给出相同的值。

例如:

00010405, 100, 0.3218 = 1

00010405, 400, 0.3218 = 1 (400 % 100 = 0)

00010405, 500, 0.3126 = 2(500%100=0,但价格不同)

00010405, 1000, 0.3126 = 2(1000 % 500 和 1000 % 100 = 0,但格式代码 100 的价格不同,因此会取值 2,因为价格相同)

Id Format Code Price Value Row
00010405 100 0.3218 1 1
00010405 400 0.3218 1 2
00010405 500 0.3126 2 3
00010405 1000 0.3126 2 4
SELECT
   Id,
   FormatCode,
   Price,
   Value,
   ROW_NUMER() OVER (
      PARTITION BY Id
      ORDER BY FormatCode
   )
FROM Table

如果我对你的理解是正确的,你想优先考虑 formatCode 乘数而不是价格。 而不是 ROW_NUMBER 你应该看看 DENSE_RANK.

描述对我来说还是有点不清楚,但如果我理解正确的话,这里有一个有效的例子:

--Setup some sample data

drop table if exists #tmp

select *
into #tmp
from (values 
('00010405',100, 0.3218 ),
('00010405',400, 0.3218 ),
('00010405',500, 0.3126 ),
('00010405',1000, 0.3126 ),
('00010405',1333, 0.3126 ),--not a multiple
('00010405',2666, 0.3126 )--multiple of previous row
) as tab(id, formatcode, price)

--Make the calculation
select 
    t.id,
    t.formatcode,
    t.price,
    DENSE_RANK() over(partition by id order by minMulti.formatCodeMin_multiplier, t.price) as Value
from #tmp t
cross apply(
    select min(formatCode) as formatCodeMin_multiplier
    from #tmp t2
    where t.id = t2.id and t.price = t2.price
    and t.formatcode % t2.formatcode = 0
) as minMulti
order by id, formatcode

诀窍是找到具有最低值的格式代码,其中当前行的值是其的倍数。