自联接以从同一表获取记录

时间:2019-12-17 12:01:56

标签: sql oracle join self-join

让我们说我有一个具有两列userid和email的表A

userid      email
abc         coMmon@email.com
xyz         common@email.com

我希望得到的结果

abc,xyz, common@email.com

我写了一个查询,如下所示

select old1.userid, new1.userid, old1.email from A old1 LEFT JOIN A new1 ON old1.email = new1.email

但这给我的结果是 abc , abc, common@email.com

任何建议都会有所帮助

3 个答案:

答案 0 :(得分:0)

您要listagg()

select listagg(userid, ',') within group (order by userid) as userids,
       email
from a
group by email;

我认为没有理由在userids的末尾添加另一个逗号,但是如果您确实需要,可以使用|| ','

我意识到,可能是的分隔符,而不是字符串中的逗号。如果要在单独的列中使用成对的用户ID,则可以使用自联接

select a1.userid, a2.userid, a1.email
from a a1 join
     a a2
     on a1.email = a2.email and a1.userid < a2.userid;

答案 1 :(得分:0)

当您说 old new 时,表示时间顺序。您需要一些确定顺序的列,现在我们不知道abc是否早于xyz。如果您有这样的列(比如说seq),则可以在查询中使用它来查找上一个值。您可以进行自我加入或更好地使用lag()函数:

select lag(userid) over (partition by email order by seq) prev_userid, userid, email 
  from a 

dbfiddle

答案 2 :(得分:0)

根据您的预期输出,它可能会对您有所帮助。

请检查

DECLARE @table TABLE
(
    userid varchar(20),
    email varchar(30)
);
INSERT INTO @table VALUES('abc','common@email.com'),('xyz','common@email.com')

SELECT a1.userid AS UserID1,a2.userid AS UserID2, a1.email
FROM @table a1 
JOIN @table a2
     on a1.email = a2.email and a1.userid < a2.userid;
  
      
  1. 选择查询输出
  2.   

enter image description here

SELECT CONCAT(a1.userid,',',a2.userid) AS userid, a1.email
FROM @table a1 
JOIN @table a2
     on a1.email = a2.email and a1.userid < a2.userid;
  
      
  1. 选择查询输出
  2.   

enter image description here

SELECT CONCAT(a1.userid,',',a2.userid,', ',a1.email) AS Result
FROM @table a1 
JOIN @table a2
     ON a1.email = a2.email and a1.userid < a2.userid;
  
      
  1. 选择查询输出
  2.   

enter image description here