sql - 流畅地在 t-sql 中添加值

标签 sql sql-server tsql

我有一个这样的表:

Items   Date        Price
1       2016-01-01  10
1       2016-01-02  15
1       2016-01-03  null
1       2016-01-04  null
1       2016-01-05  8
1       2016-01-06  null
1       2016-01-07  null
1       2016-01-08  null
2       2016-01-01  14
2       2016-01-02  7
2       2016-01-03  null
2       2016-01-04  null
2       2016-01-05  16
2       2016-01-06  null
2       2016-01-07  null
2       2016-01-08  5

现在我想更新空值。空值前后的价格差必须均匀相加。

示例:

1       2016-01-02  15   to
1       2016-01-05  8

15 到 8 = -7

-7/3 = -2,333333

1       2016-01-02  15
1       2016-01-03  12,6666
1       2016-01-04  10,3333
1       2016-01-05  8

不应该用光标来制作。帮助表就可以了。

最佳答案

这确实是您需要在 lag()lead() 上使用ignore nulls 选项的地方。唉。

另一种方法是使用外部应用:

select t.*,
       coalesce(t.price,
                tprev.price +
                 datediff(day, tprev.date, t.date) * (tnext.price - tprev.price) / datediff(day, tprev.date, tnext.date)
               ) as est_price
from t outer apply
     (select top 1 t2.*
      from t t2
      where t2.item = t.item and
            t2.date <= t.date and
            t2.price is not null
      order by t2.date desc
     ) tprev outer apply
     (select top 1 t2.*
      from t t2
      where t2.item = t.item and
            t2.date >= t.date and
            t2.price is not null
      order by t2.date asc
     ) tnext ;

复杂的算术只是计算差值,除以天数,然后将天数分配到当天。

关于sql - 流畅地在 t-sql 中添加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41513712/

相关文章:

sql - 将两个连续的行合并为一列

php - 将多个产品添加到一个购物车中

c# - Entity Framework 6 和 SQL Server 序列

mysql - mysql和mariadb性能不同

sql - 使用 "Like"函数比较同一个表中的 2 列

sql - 如何在 T-SQL 中拆分以逗号分隔的重复字符串

tsql - 将整数列表分配给@var

sql - SUM SQL Server 中的总时间

mysql - friend 常用查询mysql

mysql - 使用 IN mysql 的子查询错误代码 : 1054