我在编写SQL查询时遇到以下问题:
我有一个由列组成的表:id,日期(dd / mm / yyyy),电话和电子邮件。 id对于表中的每一行都是唯一的。
我需要根据日期列在手机 OR 电子邮件列中查找重复项来查找重复记录。 即,确定记录中的电子邮件或电话是否已存在于上一个日期。如果是,请将其标记为重复。
答案 0 :(得分:1)
Prob做这样的事情:
select a.id, a.date, a.phone, a.email,
case when b.phone is not null or c.email is not null then 'Duplicate' else 'Unique' end as flag
from table a
left join table b on (a.phone = b.phone and a.date > b.date)
left join table c on (a.email = c.email and a.date > c.date)
如果您在电话,电子邮件和日期的数据集中存在欺骗,这可能会导致多行返回,因此您可能需要在联接中进行子选择。
例如
left join (select distinct phone, date from table) b on (a.phone = b.phone and a.date > b.date)
原文
我已经考虑了更多,如果以前有手机或电子邮件的实例,你会在联接上获得重复的行。
这应该更好:
select a.id, a.date, a.phone, a.email,
case when a.phone is null and a.email is null then null
when sum(case when b.phone is not null or c.email is not null then 1 else 0 end) > 0 then 'Duplicate' else 'Unique' end as flag
from table a
left join table b on (a.phone = b.phone and a.date > b.date)
left join table c on (a.email = c.email and a.date > c.date)
group by a.id, a.date, a.phone, a.email