sql-server - MS SQL 2005 - 用线性插值替换空值

标签 sql-server

下面有一组数据,其中包含 MS SQL 2005 中的日期和值。某些日期的值为 NULL。使用线性插值填充空值的最佳方法是什么?

Date,ShortName,LongName,Value
12/31/2012,ABC,Test1,-4.0
12/31/2012,XYZ,Test2,-8.1
1/2/2013,ABC,Test1,NULL
1/2/2013,XYZ,Test2,NULL
1/3/2013,ABC,Test1,NULL
1/3/2013,XYZ,Test2,NULL
1/4/2013,ABC,Test1,-9.6
1/4/2013,XYZ,Test2,-13.0
1/7/2013,ABC,Test1,NULL
1/7/2013,XYZ,Test2,NULL
1/8/2013,ABC,Test1,NULL
1/8/2013,XYZ,Test2,NULL
1/9/2013,ABC,Test1,NULL
1/9/2013,XYZ,Test2,NULL
1/10/2013,ABC,Test1,NULL
1/10/2013,XYZ,Test2,NULL
1/11/2013,ABC,Test1,-7.1
1/11/2013,XYZ,Test2,-12.7

最佳答案

这是一种似乎给我带来不错结果的方法:

select *
from tests
where value is not null
union all
select t.Date
  , t.ShortName
  , t.LongName
  , Value = p.Value + (n.Value - p.Value)
    * (cast(datediff(dd, p.Date, t.Date) as decimal(16,1)))
    / (cast(datediff(dd, p.Date, n.Date) as decimal(16,1)))
from tests t
  cross apply
  (
    select top 1 p.date, p.value
    from tests p
    where p.Value is not null
      and t.shortname = p.shortname
      and t.date > p.date
    order by p.date desc
  ) p
  cross apply
  (
    select top 1 n.date, n.value
    from tests n
    where n.Value is not null
      and t.shortname = n.shortname
      and t.date < n.date
    order by n.date
  ) n
where t.Value is null
order by ShortName, Date

SQL Fiddle with demo .

另一个SQL Fiddle带有更多调试信息,即我使用的 x、x0、y 等值。

虽然您的数据没有周末,但我认为该行也包括周末。如果不是,我确信可以调整查询。

关于sql-server - MS SQL 2005 - 用线性插值替换空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16743713/

相关文章:

sql-server - Sql Server中的大事务,有什么问题吗?

sql - 如何使用 SQL UPDATE 语句将 1 年添加到 DATETIME 列?

sql-server - 查看存储过程是否已经在运行

SQL Server : Using binary_checksum column on a table best practice

sql - 从每个类别中至少选择一个但不超过一个,并且没有与另一列重复

c# - SQL - 将 NULL 插入 DateTime

sql - STIntersection 结果为 STIntersects = 0

sql-server - 覆盖 SQL Server 中 bigint 数据类型的最大值

sql - SQL 服务器中的 FOR XML PATH 和 [text()]

mysql - 我需要在 LINKED 服务器中将查询从 Mssql 更新到 Mysql