Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 从可变起点线性外推值至0_Sql_Sql Server_Statistics_Extrapolation - Fatal编程技术网

Sql 从可变起点线性外推值至0

Sql 从可变起点线性外推值至0,sql,sql-server,statistics,extrapolation,Sql,Sql Server,Statistics,Extrapolation,我想构建一个查询,它允许我灵活地从最后一个已知值开始线性推断一个0岁以下的数字。该表(见下文)有两列,即列年龄和体积。我11岁时的最后一个已知体积是321.60,我如何以年为单位将321.60线性外推到0岁?另外,我希望以允许年龄变化的方式设计查询。例如,在另一个场景中,最后一个卷在27岁。我一直在试验铅函数,因此我可以在10岁时外推体积,但该函数不允许我外推到0。我如何设计一个查询(a)允许我线性外推到0岁,(B)是灵活的,允许线性外推的不同起点 SELECT [age],

我想构建一个查询,它允许我灵活地从最后一个已知值开始线性推断一个0岁以下的数字。该表(见下文)有两列,即列年龄和体积。我11岁时的最后一个已知体积是321.60,我如何以年为单位将321.60线性外推到0岁?另外,我希望以允许年龄变化的方式设计查询。例如,在另一个场景中,最后一个卷在27岁。我一直在试验铅函数,因此我可以在10岁时外推体积,但该函数不允许我外推到0。我如何设计一个查询(a)允许我线性外推到0岁,(B)是灵活的,允许线性外推的不同起点

SELECT     [age], 
           [volume], 
           Concat(CASE WHEN volume IS NULL THEN ( Lead(volume, 1, 0) OVER (ORDER BY age) ) / ( age + 1 ) * 
           age END, volume) AS 'Extrapolate' 
    FROM   tbl_volume

+-----+--------+-------------+
| Age | Volume | Extrapolate |
+-----+--------+-------------+
|   0 | NULL   | NULL        |
|   1 | NULL   | NULL        |
|   2 | NULL   | NULL        |
|   3 | NULL   | NULL        |
|   4 | NULL   | NULL        |
|   5 | NULL   | NULL        |
|   6 | NULL   | NULL        |
|   7 | NULL   | NULL        |
|   8 | NULL   | NULL        |
|   9 | NULL   | NULL        |
|  10 | NULL   | 292.363     |
|  11 | 321.60 | 321.60      |
|  12 | 329.80 | 329.80      |
|  13 | 337.16 | 337.16      |
|  13 | 343.96 | 343.96      |
|  14 | 349.74 | 349.74      |
+-----+--------+-------------+

对于这种情况,可以使用带有空
over()
的窗口函数。举个简单的例子:

create table t(j int, k decimal(3,2));
insert t values (1, null), (2, null), (3, 3), (4, 4);

select  j, j * avg(k / j) over ()       
from    t

请注意,
avg()
忽略空值。

如果我假设
0处的值为
0
,则可以使用简单的算术。这似乎在您的情况下起作用:

select t.*,
       coalesce(t.volume, t.age * (t2.volume / t2.age)) as extrapolated_volume
from t cross join
     (select top (1) t2.*
      from t t2
      where t2.volume is not null
      order by t2.age asc
     ) t2;

是一个Dfiddle

请解释计算“292.363”所需的数学函数。