我想设计一个 sql 代码来删除重复项,唯一的是它比只使用 CTE 复杂一点

I want to design a sql code to delete duplicates, the only thing is it is a bit more complex than just using a CTE

下面是 table 的样子

PatientKey     Accotno     Date    EHR
yur567          123         4/5    HUB
yur567          123         4/5    REF 
yur789          780         4/9    HUB
yte789          567         7/8    HUB
yte765          569         7/7    REF
yte765          564         7/8    HUB
yur789          654         4/5    REF
yur789          654         4/5    HUB

我想写一个 sql 代码,以便在两行中 patientKey 相同的地方,删除 REF 并保留 HUB。同时我不想删除其他 'REF' 数据。我只想删除其他REF(未重复删除)

的数据

期望的输出:

PatientKey     Accotno     Date    EHR
yur567          123         4/5    HUB
yur789          780         4/9    HUB
yte789          567         7/8    HUB
yte765          569         7/7    REF
yte765          564         7/8    HUB
yur789          654         4/5    HUB

如果您在输出中看到所有具有 EHR=REF 的数据都已删除,现在我们有唯一的行。

您可以使用 exists:

delete t
from mytable t
where ehr = 'REF' and exists (
    select 1
    from mytable t1
    where t1.PatientKey = t.PatientKey and t1.date = t.date and t1.ehr = 'HUB'
)

这将删除“REF”,对于相同的 datePatientKey,存在另一个“HUB”行。

I want to write a sql code so that where the patientKey is the same in both rows, delete REF and Keep HUB.

你可以用exists来回答这个问题:

delete from t
    where t.ehr = 'REF' and
          exists (select 1
                  from t t2
                  where t2.patientid = t.patientid and t2.ehr = 'HUB'
                 )

但是根据您的结果,您似乎还想考虑其他列:

delete from t
    where t.ehr = 'REF' and
          exists (select 1
                  from t t2
                  where t2.patientid = t.patientid and
                        t2.Accotno = t.Accotno and
                        t2.date = t.date and
                        t2.ehr = 'HUB'
                 )