选择具有相同ID /电子邮件但在其他表
中具有不同值的行我有两个表:人和电子邮件,现在有相同值的邮件地址,以及具有不同值的人员/ ID。
有人能说出如何为此编写SQL查询吗?我试过但我无法弄明白。我找到了一些答案,但随后总是在同一张表中找到匹配
喜欢这个
Table_person. Table_email
1 email@persoon1
2 email@persoon2
3 email@persoon3
4 email@persoon1
5 email@persoon5
6 email@persoon2
输出应为
Table_person Table_email
1 email@persoon1
4 email@persoon1
2 email@persoon2
6 email@persoon2
答案 0 :(得分:0)
common table expression使用row_number()
;with cte as (
select *
, rn = row_number() over (partition by email order by person_id)
from email e
)
select *
from cte
where exists (
select 1
from cte i
where i.email = cte.email
and rn > 1
)
或使用exists()
select *
from email e
where exists (
select 1
from email i
where i.email = e.email
and i.person_id <> e.person_id
)
rextester演示:http://rextester.com/JHFEF82373
答案 1 :(得分:0)
希望它会帮助你
;with cte(Table_person,Table_email)
AS
(
SELECT 1,'email@persoon1' UNION ALL
SELECT 2,'email@persoon2' UNION ALL
SELECT 3,'email@persoon3' UNION ALL
SELECT 4,'email@persoon1' UNION ALL
SELECT 5,'email@persoon5' UNION ALL
SELECT 6,'email@persoon2'
)
,Cte2
AS
(
SELECT Table_person,Table_email From
(
Select Table_person,Table_email,ROW_NUMBER()OVER(Partition by Table_email Order By Table_person )Seq
from cte
)dt WHERE dt.Seq>1
)
,Final
AS
(
SELECT Table_person,Table_email From
(
Select Table_person,Table_email,ROW_NUMBER()OVER(Partition by Table_email Order By Table_email )Seq2
from cte
)dt
where dt.Seq2>1
Union ALL
SELECT Table_person,Table_email From cte2
)
SELECt Table_person,Table_email from Final