gpt4 book ai didi

SQL:删除重复记录,如果重复记录之间的日期差异小于30天

转载 作者:行者123 更新时间:2023-12-01 17:39:30 26 4
gpt4 key购买 nike

如果CreatedDate(另一列),我想从表中删除重复记录(在fkInvoiceIdfkcontractid的基础上重复)两条重复记录之间的差异小于 30 天。

WITH cte AS 
(
SELECT
Id,
fkcontractid,
fkInvoiceId,
CreatedDate,
row_number() OVER(PARTITION BY fkcontractid, fkInvoiceId ORDER BY fkcontractid) AS [rn]
from mytable left join Invoice on Invoice.pkinvoiceid = mytable.fkinvoiceid
)
delete tt from mytable tt inner join CTE as x on x.Id = tt.Id
WHERE x.[rn] > 1;

以上查询删除了重复记录(fkInvoiceIdfkcontractid),但没有获取 Date(createdDate) 的差异。

最佳答案

不知道每列来自哪些表1,发布您需要的准确查询有点棘手,但按照这些思路应该可以工作:

DELETE FROM t1
FROM mytable t1
INNER JOIN
mytable t2
ON
t1.fkcontractid = t2.fkcontractid and
t1.fkInvoiceId = t2.fkInvoiceId and
t1.ID != t2.ID and --Assuming this is the primary key
t1.CreatedDate < t2.CreatedDate and
DATEADD(day,30,t1.CreatedDate) >= t2.CreatedDate

希望逻辑足够清晰易读 - 对于每一行,我们尝试查找具有相同 fkcontractid 的另一行(ID 不匹配)并且fkInvoiceId,出现在当前行之后,但最多 30 天。

如果我们成功进行该连接,则应该删除该行(来自 t1)。

<小时/>

1如果Invoice是定义此查询的重要部分,我不清楚为什么它被LEFT JOIN编辑而不是INNER,在你的尝试中。

关于SQL:删除重复记录,如果重复记录之间的日期差异小于30天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31426761/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com