2014-09-05 49 views
1

我有以下表填寫表格日期差距

id dt2 
1 2014-09-03 00:00:00.000 
2 NULL 
3 NULL 
4 NULL 
5 2014-09-06 00:00:00.000 
6 NULL 
7 NULL 
8 2014-09-09 00:00:00.000 

我想與以前的對應日期 填補了空白點,所以我的結果集將是這樣的:

id dt2 
1 2014-09-03 00:00:00.000 
2 2014-09-03 00:00:00.000 
3 2014-09-03 00:00:00.000 
4 2014-09-03 00:00:00.000 
5 2014-09-06 00:00:00.000 
6 2014-09-06 00:00:00.000 
7 2014-09-06 00:00:00.000 
8 2014-09-09 00:00:00.000 

什麼是最簡單的方法來完成呢?

感謝

回答

0

嗯,知道了! 請參閱下面的代碼:

IF EXISTS (SELECT * FROM sys.objects 
WHERE object_id = OBJECT_ID(N'[dbo].[MyDates]')  AND type in (N'U')) 
DROP TABLE [dbo].[MyDates] 
GO 

SET ANSI_NULLS ON 
GO 

SET QUOTED_IDENTIFIER ON 
GO 

CREATE TABLE [dbo].[MyDates](
[id] [int] IDENTITY(1,1) NOT NULL, 
[dt] [datetime] NULL 
) ON [PRIMARY] 

GO 

insert into MyDates 
select convert(datetime,convert(date,getdate())) 
go 
insert into MyDates 
select null 
go 
insert into MyDates 
select null 
go 
insert into MyDates 
select convert(datetime,convert(date,getdate()+3)) 
go 
insert into MyDates 
select null 
go 
insert into MyDates 
select convert(datetime,convert(date,getdate()+8)) 
go 

--Before 
select * 
from Mydates 

--After 

;with Finish as 
(
    select isnull(b.id , a.id) id , a.dt , 
    case 
    when a.dt is null 
    then (select max(m.dt) from MyDates m where m.id <= isnull(b.id , a.id)) 
    else a.dt 
    end FullDt 
    from MyDates a 
    left join MyDates b 
    on a.dt <= b.dt 
) 

select Id, 
     max(coalesce (dt,FullDt)) FullDt 
from Finish 
group by id 
0

你需要做的只是更新查詢,填補國內空白。 這應該做的工作:

UPDATE tablename 
SET tablename.dt2 = '2014-09-03 00:00:00.000' 
WHERE tablename.dt2 IS NULL; 
+0

我不想使用硬編碼更新。請記住,我想用以前的日期替換NULLS – hkravitz 2014-09-05 06:59:35

+0

col「dt2」的數據類型是什麼? – Justin 2014-09-05 07:02:59

+0

日期時間。我需要編寫一個查詢來返回我在文章中提到的輸出 – hkravitz 2014-09-05 07:06:46