问题描述
我试图根据某些条件为我的行赋予一定数量的点数,但我不知道如何编写它。
对于给定的 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 | 格式代码 | 价格 | 值 | 行 |
---|---|---|---|---|
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,500,0.3126 ),1000,1333,--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
诀窍是找到具有最小值的格式代码,其中当前行的值是 的乘数。