SELECT *
FROM (SELECT *,
ROW_NUMBER()
OVER (
PARTITION BY ResidentID, PostedON, PayerTypeID
ORDER BY StatementNumber
) seq
FROM Statements
) s
INNER JOIN person p ON s.ResidentID = p.ID
WHERE seq > 1
AND p.FacilityID = 275
ORDER BY s.ResidentID
有一段时间的腌制将其转换为DELETE。有人知道为什么吗?
这是原始问题:
好的,所以我的代码中的一个缺陷创建了许多重复的语句,但费用相同。它们具有相同的ResidentID和相同的发布日期,但是ID和StatementID不同
ID | ResidentID | StatementID | PostedON
1 4039 10 06-15-18
2 4039 11 06-15-18
3 4039 12 06-15-18
4 4039 20 06-20-18
5 4039 21 06-20-18
6 4039 22 06-20-18
7 3456 13 06-15-18
8 3456 14 06-15-18
9 3456 15 06-15-18
10 3456 23 06-21-18
11 3456 24 06-21-18
我有一长串的很多ResidentID,这些ID在许多日期都有重复。如何删除除每个residentID每个唯一日期的StatementID最低的行以外的所有行
除了与该日期/ residentID关联的最小StatementID,我想删除所有重复项
编辑:
实际上,我可以使用更新命令,因为此表中有一个软删除列,但仍然无法使其正常工作。我很可悲。
答案 0 :(得分:1)
假设您需要从状态菜单中删除,而不是个人 那个StatementNumber是PRIMARY KEY
DELETE
FROM
Statements SX
WHERE
SX.StatementNumber IN
(SELECT s.StatementNumber
FROM (SELECT *,
ROW_NUMBER()
OVER (
PARTITION BY ResidentID, PostedON, PayerTypeID
ORDER BY StatementNumber
) seq
FROM Statements
) s
INNER JOIN person p ON s.ResidentID = p.ID
WHERE seq > 1
AND p.FacilityID = 275
ORDER BY s.ResidentID)
答案 1 :(得分:1)
将查询写为:
SELECT s.*
FROM (SELECT s.*,
ROW_NUMBER() OVER (PARTITION BY ResidentID, PostedON, PayerTypeID
ORDER BY StatementNumber
) as seqnum
FROM Statements s
WHERE EXISTS (SELECT 1
FROM person p
WHERE s.ResidentID = p.ID AND p.FacilityID = 275
) s
WHERE seq > 1;
Voila!这是可更新的CTE。您可以将其删除。我可以这样说:
with todelete as (
SELECT s.*,
ROW_NUMBER() OVER (PARTITION BY ResidentID, PostedON, PayerTypeID
ORDER BY StatementNumber
) as seqnum
FROM Statements s
WHERE EXISTS (SELECT 1
FROM person p
WHERE s.ResidentID = p.ID AND p.FacilityID = 275
)
delete todelete
where seqnum > 1;
您可以随时将其更改为update
:
with toupdate as (
SELECT s.*,
ROW_NUMBER() OVER (PARTITION BY ResidentID, PostedON, PayerTypeID
ORDER BY StatementNumber
) as seqnum
FROM Statements s
WHERE EXISTS (SELECT 1
FROM person p
WHERE s.ResidentID = p.ID AND p.FacilityID = 275
)
update toupdate
set softdelete = 1
where seqnum > 1;