简体   繁体   中英

Self join to get the records from the same table

Lets say I have a table A with 2 columns userid and email

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

I would like have result as

abc,xyz, common@email.com

I wrote a query as below

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

But this gives me the result as abc , abc, common@email.com

Any suggestion would be helpful

You want listagg() :

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

I see no reason to add another comma at the end of userids , but you can use || ',' || ',' if you really want one.

I realize that , might be a column separator and not a comma in a string. If you want pairs of userids in separate columns, then you can use a self-join

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

When you say old and new it means chronological order. You need some column which determines order, now we don't know if abc is older than xyz . If you have such column (let's say seq ) you can use it in your query to find previous value. You can make self-join or better use lag() function:

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

dbfiddle

As per your expected output maybe it helps you.

Please check this

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. Select Query Output

在此处输入图片说明

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. Select Query Output

在此处输入图片说明

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. Select Query output

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM