我进行了以下设置
create table #TestEmailTable
(companyId int
,username varchar(255)
,emailAddress varchar(255))
insert #TestEmailTable
values (570599,'[email protected]','[email protected]')
,(570589,'[email protected]','[email protected]')
,(109350,'[email protected]','[email protected]')
,(109350,'[email protected]','[email protected]')
我试图找到公司 ID 相同的数据行,并且与不同用户的用户名列进行比较时,电子邮件地址列中存在重复的值。因此,在此示例中,第一行数据不会被视为重复项。但第 3 行和第 4 行将被视为重复,因为 companyId 相同,并且第 3 行用户名列中的用户名“[email protected]”与 emailAddress 列中的“[email protected]”相同在第 4 行。
以下是我所做的尝试,但没有成功
select a.*,b.hasADuplicate
from #TestEmailTable a
inner join (
select companyId,username ,count(*) hasADuplicate
from #TestEmailTable
group by companyId,username
) b on b.companyId = a.companyId and b.username = a.emailAddress
以下是我想要实现的目标
companyId | username |emailAddress | hasADuplicate
---------------------------------------------------------------------------
109350 |[email protected] |[email protected] | 1
SELECT a.companyId, a.username, a.emailAddress, COUNT(*) AS hasADuplicate
FROM #TestEmailTable a
JOIN #TestEmailTable b ON a.companyId = b.companyId
AND a.username = b.emailAddress
AND a.username <> a.emailAddress
GROUP BY a.companyId, a.username, a.emailAddress
HAVING COUNT(*) > 0;