填写表格中的日期差距

时间:2014-09-05 06:48:41

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

我有下表

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

我想用之前的相应日期填写Null 所以我的结果集看起来像这样:

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

实现这一目标的最简单方法是什么?

由于

2 个答案:

答案 0 :(得分:0)

您只需执行更新查询即可填补空白。 这应该做的工作:

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

答案 1 :(得分: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