SQL-更新查询-更新到下一个非NULL的日期值

时间:2019-03-07 16:44:31

标签: sql sql-server

我有一堆当前在具有NULL值的日期(即在那些特定日期没有可用数据)的值。

如何将这些值更新到有数据的下一个日期?

我目前有一个选择查询,该查询突出显示日期为NULL值(或由小于0的值定义的错误数据)的所有值:

select * from table1 a 
left join table2 b on a.id=b.id and a.date=b.date --joins dates table to main data set

where a.id in (select c.id from table3 c
left join table4 d on c.id=d.id where c.value = 000000) -- sub query identifying sub set of data I want to use as 'id' list

and a.date is not NULL and a.date > '1900-01-01' --a.date not NULL just identifies illegitimate date values that I don't want to see
and (b.value is NULL or b.value < 0) --identifies legitimate values that fall on dates where there are NULL values or false dates

因此,此查询为我提供了所选数据集中所有出现在具有错误数据或NULL值的日期的值。我在查询中使用了更多的“ where”和“ and”变量,但这有望为理解提供良好的基础。

我想将所有这些值更新为将来非NULL的下一个日期(即具有合法数据)。

这只是我所想的一个小例子: update table1 set date =(假设这里会有某种select子查询来定义不为NULL的下一个日期值 )。

还有另一点需要考虑:下一个值不为NULL的日期是动态的-从给定日期开始可能是2天,但可能是2年。

2 个答案:

答案 0 :(得分:2)

/*I would create a variable table @mytab in which I will put sample sample data
with dates and null*/
--Kamel Gazzah
--07/03/2019
declare @mytab as table(id int identity(1,1),mydate  date)

insert into @mytab values('01/01/2018')
insert into @mytab values(NULL)
insert into @mytab values('01/05/2018')
insert into @mytab values('01/07/2018')
insert into @mytab values('01/08/2018')
insert into @mytab values(NULL)
insert into @mytab values(NULL)
insert into @mytab values(NULL)
insert into @mytab values('01/08/2018')

select * from @mytab


--First Method with **OUTER APPLY**
update t1 set mydate=t2.mydate
--select t1.*,t2.mydate 
from @mytab t1
OUTER APPLY (select top 1 * from @mytab where mydate is not null and id > t1.id order by mydate) t2 
where t1.mydate is null



--SCOND METHOD WITH **LEFT OUTER JOIN**
update ta set mydate=tc.mydate
--select ta.id,tc.mydate 
from @mytab ta 
inner join(
select id1,min(id2) id2 from(
select t1.id id1,t2.id id2,t2.mydate from @mytab t1
left outer join @mytab t2 on t2.id > t1.id and t2.mydate is not null
where t1.mydate is null) v group by id1) tb on ta.id=id1
inner join @mytab tc on  tb.id2=tc.id

select * from @mytab

答案 1 :(得分:0)

您可以使用Apply来解决它

UPDATE T
SET Date = N.Date
FROM yourTable T
OUTER APPLY (
    SELECT TOP 1 Date FROM YourTable 
    WHERE ........
    ORDER BY ..........
) N
WHERE T.Date IS NULL