检测重叠日期并更新最新记录SQL Server 2008
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了检测重叠日期并更新最新记录SQL Server 2008相关的知识,希望对你有一定的参考价值。
我希望能够检测所有记录(一些重复)并将重叠的记录(之后上传的记录)标记为OVER
。为此,我有SELECT返回现有的重叠记录,CTE将此列设置为OVER
。
我的问题是调整select查询以使用此值标记最新值并将其存储在cte中,因为我不熟悉SQL。
选择:
select t.*
from testtable t where exists
(select 1 from testtable t2
where t.idd = t2.idd
AND t.id<>t2.id
AND t2.beg <= t.end
AND t.beg <= t2.end)
完成CTE的一半:
;with cte
as (select t.*, Row_number() over (partition by idd order by date_uploaded desc) RN
from testtable as t)
update cte set overlapped = 'OVER'
where RN > 1
and (overlapped is null or overlapped <> 'UNIQUE')
示例数据,它应该是什么样子:
overlapped ID idd iduser iddate name beg end date_uploaded
UNIQUE 52 -1907372231 666 201802 sol 2018-09-01 2018-09-10 2018-09-12
OVER 53 -1907372231 666 201802 sol 2018-09-10 2018-09-12 2018-09-13
注意第53行如何将BEG日期与END重叠
对我的问题有任何帮助,非常感谢。
答案
当您从中选择时,请使用CASE表达式,而不是更新CTE:
;with cte
as (select t.*, Row_number() over (partition by idd order by date_uploaded desc) RN
from testtable as t)
SELECT CASE
WHEN RN > 1 and (overlapped is null or overlapped <> 'UNIQUE') THEN 'OVER'
ELSE overlapped
END AS overlapped
FROM cte
以上是关于检测重叠日期并更新最新记录SQL Server 2008的主要内容,如果未能解决你的问题,请参考以下文章