【发布时间】:2019-11-21 06:36:47
【问题描述】:
我目前正在查询一个缺少索引的表。
这是一些示例数据:
id dStartDate
126 2010-04-22 00:00:00.000
127 NULL
128 2010-04-29 00:00:00.000
129 2010-05-03 00:00:00.000
130 NULL
131 NULL
132 NULL
133 2010-04-29 00:00:00.000
134 NULL
135 NULL
136 2010-04-29 00:00:00.000
137 NULL
138 NULL
139 2010-04-29 00:00:00.000
140 NULL
141 2010-04-29 00:00:00.000
142 2010-04-29 00:00:00.000
143 NULL
144 NULL
我使用以下脚本来获取缺失的索引:
declare @id int
declare @maxid int
set @id = 1
select @maxid = max(idJCMaster) from _btblJCMaster
declare @IDseq table (id int)
while @id < @maxid --whatever you max is
begin
insert into @IDseq values(@id)
set @id = @id + 1
end
select
s.id
from @IDseq s
left join _btblJCMaster t on s.id = t.idJCMaster
where t.idJCMaster is null
以上工作完美,但是,我想查看上一条记录(非空)日期,以了解该记录何时被删除...
我把上面的脚本改成了这样:
declare @id int
declare @maxid int
set @id = 1
select @maxid = max(idJCMaster) from _btblJCMaster
declare @IDseq table (id int)
while @id < @maxid --whatever you max is
begin
insert into @IDseq values(@id)
set @id = @id + 1
end
select
s.id
, t.dStartDate
from @IDseq s
left join _btblJCMaster t on s.id = t.idJCMaster
我得到的结果是这样的:
可以看出,有时这些特定索引的缺失会超过记录...
我不确定如何更改脚本以显示上一个日期(在 null 之前)。
在这个例子中,我的预期结果是:
请协助预期结果?
非常感谢您的帮助!
编辑
在Ankit的帮助下,尝试了以下(他的回答):
declare @id int
declare @maxid int
set @id = 1
select @maxid = max(idJCMaster) from _btblJCMaster
declare @IDseq table (id int)
while @id < @maxid --whatever you max is
begin
insert into @IDseq values(@id)
set @id = @id + 1
end
select
s.id
, (SELECT MAX(dStartDate)
FROM _btblJCMaster
WHERE id >= t1.idJCMaster) dStartDate
from @IDseq s
left join _btblJCMaster t1 on s.id = t1.idJCMaster
但我仍然收到NULLS。
然后我继续尝试他的第一个答案,稍微改变LAG 函数并添加LEAD,带有3 个CTE,但我仍然得到NULLS:
declare @id int
declare @maxid int
set @id = 1
select @maxid = max(idJCMaster) from _btblJCMaster
declare @IDseq table (id int)
while @id < @maxid --whatever you max is
begin
insert into @IDseq values(@id)
set @id = @id + 1
end
;with cte (id, dStartDate, idJCMaster)
as
(
select
s.id
, ISNULL(dStartDate, isnull(LAG(dStartDate) OVER(order by s.id),LEAD(dStartDate) OVER(order by s.id)))
, IdJCMaster
from @IDseq s
left join _btblJCMaster t1 on s.id = t1.idJCMaster
)
, cte2 (id,dStartDate, idJCMaster)
as
(
select
id
, isnull(dStartDate,LAG(dStartDate) OVER(order by id))
, idJCMaster
from cte
)
, cte3 (id,dStartDate, idJCMaster)
as
(
select
id
, isnull(dStartDate,LEAD(dStartDate) OVER(order by id))
, idJCMaster
from cte2
)
select
id
, isnull(dStartDate,LAG(dStartDate) OVER(order by id))
from cte3
where idJCMaster is null
没有其他更简单的方法可以做到这一点吗?
【问题讨论】:
标签: tsql sql-server-2017