2015-04-06 38 views
1

我試圖編寫一個查詢,該查詢返回所有後續日期旁邊的最後一個非空值,直到遇到新的非空值。輸入表看起來像這樣:SQL查詢按日期運行當前值

DATE   VALUE 
==========  ====== 
01/01/2015  1 
02/01/2015  NULL 
03/01/2015  NULL 
04/01/2015  2 
05/01/2015  NULL 

而且我想在查詢結果表是這樣的:

DATE   CURRENT VALUE 
==========  ============= 
01/01/2015  1 
02/01/2015  1 
03/01/2015  1 
04/01/2015  2 
05/01/2015  2 

我已經嘗試了一個答案搜索周圍,但我還沒有拿出任何東西。如果這種問題很普遍,請原諒我。由於

+0

數據中的缺口/缺失日期?如果是這樣的話,那麼你可能想要預先建立一個日期表並將其用於外部應用。 –

回答

3

也許最簡單的方法是使用outer apply

select t.date, coalesce(t.value, t2.value) as current_value 
from table t outer apply 
    (select top 1 t2.value 
     from table t2 
     where t2.value is not null and 
      t2.date <= t.date 
     order by t2.date desc 
    ) tt; 

如果你知道這些值都在增加,然後在SQL Server 2012+可以使用max()

select date, max(value) over (order by date) as current_value 
from table t; 
1

另一種方式,如果日期字段是unique,並且是increasing by onewith no gap那麼您可以使用recursive cte

with cte (dt,value) as 
(
select top 1 date , value from tbl where value is not null 
union all 
select t.date, isnull(t.value,cte.value) 
from tbl t 
join cte on t.date=dateadd(month,1,cte.dt) 
) 
select * from cte 

the FIDDLE DEMO

1

如果在數據的空行被最多一個排的時間,你可以使用LAGCOALESCE重複上一行的值:

SELECT t1.Date, COALESCE(t1.Value, LAG (Value, 1) OVER (ORDER BY t1.Date ASC)) 
FROM Table1 t1 
ORDER By T1.Date ASC; 

不幸的當然,你的數據有兩行或更多行的差距,這意味着你需要繼續擴展COALESCING,這導致了一些非常可怕的事情:

SELECT t1.Date, 
     COALESCE(t1.Value, 
       LAG (Value, 1) OVER (ORDER BY t1.Date ASC), 
       LAG (Value, 2) OVER (ORDER BY t1.Date ASC), 
       ...) 
FROM Table1 t1 
ORDER By T1.Date ASC 

哪一個不是通用的。