2010-06-10 3 views
4

다음 표는 하루에 값을 기록합니다. 문제는 때로는 며칠이 빠져 있다는 것입니다. 다음 소스 테이블에서 SQL Server 보완 누락 된 행

그래서 선형 보간법을 사용하여

  1. 반환 누락 된 일
  2. 누락 된 값을 계산 : 나는 SQL의 의지 쿼리를 작성하려는

    Date   Value 
    -------------------- 
    2010/01/10  10 
    2010/01/11  15 
    2010/01/13  25 
    2010/01/16  40 
    

    반환하고 싶습니다.

    Date   Value 
    -------------------- 
    2010/01/10  10 
    2010/01/11  15 
    2010/01/12  20 
    2010/01/13  25 
    2010/01/14  30 
    2010/01/15  35 
    2010/01/16  40 
    

    도움을 주시면 대단히 감사하겠습니다.

답변

3
declare @MaxDate date 
declare @MinDate date 

select @MaxDate = MAX([Date]), 
     @MinDate = MIN([Date]) 
from Dates 

declare @MaxValue int 
declare @MinValue int 

select @MaxValue = [Value] from Dates where [Date] = @MaxDate 
select @MinValue = [Value] from Dates where [Date] = @MinDate 

declare @diff int 
select @diff = DATEDIFF(d, @MinDate, @MaxDate) 

declare @increment int 
set @increment = (@MaxValue - @MinValue)/@diff 

select @increment 

declare @jaggedDates as table 
(
    PID INT IDENTITY(1,1) PRIMARY KEY, 
    ThisDate date, 
    ThisValue int 
) 

declare @finalDates as table 
(
    PID INT IDENTITY(1,1) PRIMARY KEY, 
    [Date] date, 
    Value int 
) 

declare @thisDate date 
declare @thisValue int 
declare @nextDate date 
declare @nextValue int 

declare @count int 
insert @jaggedDates select [Date], [Value] from Dates 
select @count = @@ROWCOUNT 

declare @thisId int 
set @thisId = 1 
declare @entryDiff int 
declare @missingDate date 
declare @missingValue int 

while @thisId <= @count 
begin 
    select @thisDate = ThisDate, 
      @thisValue = ThisValue 
    from @jaggedDates 
    where PID = @thisId 

    insert @finalDates values (@thisDate, @thisValue) 

    if @thisId < @count 
    begin 
     select @nextDate = ThisDate, 
      @nextValue = ThisValue 
     from @jaggedDates 
     where PID = @thisId + 1 

     select @entryDiff = DATEDIFF(d, @thisDate, @nextDate) 
     if @entryDiff > 1 
     begin 
      set @missingDate = @thisDate 
      set @missingValue = @thisValue 
      while @entryDiff > 1 
      begin 
       set @missingDate = DATEADD(d, 1, @missingDate) 
       set @missingValue = @missingValue + @increment 
       insert @finalDates values (@missingDate, @missingValue) 
       set @entryDiff = @entryDiff - 1 
      end 
     end 
    end 

    set @thisId = @thisId + 1 
end 

select * from @finalDates 
+0

감사합니다. GalacticJello 당신은 별입니다. 내가 한 것. – SausageFingers

+1

이 솔루션은 테이블의 첫 번째 항목과 마지막 항목을 기반으로 한 요소의 누락 된 값을 계산합니다. 주어진 행에서 이전 값과 다음 값을 기반으로 누락 값을 다시 계산하기 위해 코드를 약간 수정했습니다. 행 뒤에 : "여기서 PID = @thisId + 1" 행 추가 : "@diff = DATEDIFF (d, @thisDate, @nextDate) 선택" "@increment = (@nextValue - @thisValue)/@diff " – SausageFingers

관련 문제