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



我正试图根据某些条件给我的行提供一定数量的点,我不知道该怎么写

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

例如:

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,因为它具有相同的价格)

3

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

描述对我来说仍然有点不清楚,但如果我理解正确的话,这里有一个工作示例:

--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
技巧是找到具有最小值的格式代码,其中当前行的值是。 的乘数。

最新更新