SQL - 从前一个值插入周末和假日的数据行

时间:2015-02-18 14:13:39

标签: sql sql-server sql-server-2008

我相信我有这个(?)的逻辑,但不是100%肯定语法,如果这将工作。希望在周末和假日(空白)填充自己的前一天数据行数据。因此,如果我有一组看起来像这样的数据,已按日期排序

DATE              VALUE           PERCENT            
12/31/2014        100             .01  
1/2/2015          150             .015
1/5/2015          200             .015
1/6/2015          200             .015
1/7/2015          200             .015
1/8/2015          250             .015
1/9/2015          300             .021
1/12/2015         400             .022
1/13/2015         400             .022

因此,对于上面的这组数据,我想循环并插入以下行:

DATE              VALUE           PERCENT            
1/1/2015          100             .01   (carries over the 12/31 values)
1/3/2015          150             .015  (carries over the 1/2 values)   
1/4/2015          150             .015  (carries over the 1/2 or 1/3 values)
1/10/2015         300             .021  (carries over the 1/9 values) 
1/11/2015         300             .021  (carries over the 1/10 values)

这是我建议的伪代码:

DECLARE @CurrDate datetime
DECLARE @VALUE int
DECLARE @PERCENT decimal(20,2)

SET @CurrDate = Min(Date) from table
SET @VALUE = value from table where Date = @CurrDate
SET @PERCENT = percent from table where Date =@CurrDate


For each Date in table

  @CurrDate = CurrDate + 1

    If exists (SELECT Date From table where Date = @CurrDate) then 

       @VALUE    = select value from table where date = @currDate
       @PERCENT  = select percent from table where date = @currDate          

    next

ELSE

    INSERT INTO table (SELECT @CurrDate, @VALUE, @PERCENT)

END

NEXT       

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:2)

你可以重复这样的插入:

insert into table(date, value, percent)
    select dateadd(day, 1, date)
    from table
    where not exists (select 1
                      from table t2
                      where t2.date = dateadd(day, 1, t.date)
                     );

您可能需要这样做两到三次,具体取决于您缺少的连续天数。

相关问题