生成缺失日期的平均增长数据

时间:2014-06-24 20:01:17

标签: sql-server

我在MSSQL 2008 R2中工作,需要一些生成数据的帮助

我有一个范围表,看起来像这样

CREATE TABLE [dbo].[Weight](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Date] [datetime] NULL,
    [Weight] [decimal](18, 2) NULL,
)

我的数据看起来像这样

INSERT INTO [Weight] VALUES ('2014-05-07', 1)
INSERT INTO [Weight] VALUES ('2014-05-10', 20)
INSERT INTO [Weight] VALUES ('2014-05-15', 80)
INSERT INTO [Weight] VALUES ('2014-05-25', 100)

好了,我现在要做的是生成缺失日期的平均增长数据。 我想要插入临时表中的缺少日期

这是最终结果的样子。

Date        Weight
2014-05-07  1
2014-05-08  7.33
2014-05-09  13.66
2014-05-10  20
2014-05-11  32
2014-05-12  44
2014-05-13  56
2014-05-14  68
2014-05-15  80
2014-05-16  82
2014-05-17  84
2014-05-18  86
2014-05-19  88
2014-05-20  90
2014-05-21  92
2014-05-22  94
2014-05-23  96
2014-05-24  98
2014-05-25  100

1 个答案:

答案 0 :(得分:3)

  SELECT
    DATEADD(day,[n],[date]) [Date],
    [weight] + ISNULL([n]*([next_weight]-[weight])/[count],0) [Weight]
  FROM [dbo].[Weight] t1
  OUTER APPLY (
    SELECT TOP 1
      DATEDIFF(day,t1.[date],[date]) [count],
      [weight] [next_weight]
    FROM [dbo].[Weight]
    WHERE [date] > t1.[date]
    ORDER BY [date]
  ) t2
  CROSS APPLY (
    SELECT TOP(ISNULL([count],1)) 
      ROW_NUMBER() OVER(ORDER BY (SELECT 1))-1 [n]
    FROM master.dbo.spt_values
  ) t3

<强> SQL Fiddle demo