有没有办法在自定义范围内找到数字的位置?
例如,我有一个从-10.0到5.0的数字列表,其中包含1个小数精度。 范围内的总数为151(包括起始值和结束值)。 -10.0位于第1位,5.0位于第151位。我正在尝试查找一个查询,该查询可以给出该范围内2.5(即位置126)的位置。
表格结构:
id |来自|到
1 | -10.0 | 5.0
2 | 658.5 | 835.0
3 | 32.5 | 65.3
4 | -32.5 | 65.0
增量默认为0.1
答案 0 :(得分:2)
这是另一个将问题集拼接在一起的尝试。
事情的核心,它只是一个数学问题:
-- Proof of concept
DECLARE
@First decimal(9,2)
,@Last decimal(9,2)
,@Increment decimal(9,2)
,@NewValue decimal(9,2)
,@Position int
SET @First = -10.0
SET @Last = 5.0
SET @Increment = .1
SET @NewValue = 5.0
SET @Position = (@NewValue - @First) / @Increment + 1
PRINT @Position
GO
接下来,假设一个表具有First和Last值,下面将生成一个" Position"表中每行的值:
DECLARE @Test as TABLE
(
Id int not null identity(1,1)
,First decimal(9,2) not null
,Last decimal(9,2) not null
)
INSERT @Test (First, Last) values
(-10.0, 5.0)
,(685.5, 835.0)
,(32.5, 65.3)
,(-32.5, 65)
DECLARE
@TargetValue decimal(9,2)
,@Increment decimal(9,2)
SET @TargetValue = 0
SET @Increment = .1
SELECT
Id
,First
,Last
,case
when @TargetValue < First then null
when @TargetValue > Last then null
else cast((@TargetValue - First) / @Increment + 1 as int)
end Position
from @Test
我希望对其中一个或另一个进行修改可以帮助解决实际问题。
答案 1 :(得分:1)
这可以让您了解计算结果:
DECLARE @rangestart decimal(18,1) = -10.0;
DECLARE @rangeend decimal(18,1) = 5.0;
DECLARE @count int = @rangeend * 10 - @rangestart * 10 +1
DECLARE @search decimal(18,1) = 2.5;
SELECT @count - (@search * 10) AS position
所以你的查询看起来像这样:
SELECT ((end_to * 10 - start_from * 10 + 1) - (2.5 * 10)) AS position FROM yourTable