简体   繁体   中英

how can i find unique conversation from table in sql

I Have this table:

[Messages table]

1

I need to find the number of uniqe conversation - conversation is define as senderid sent msg to reciverid, and reciverid has replied (no matter how many times or the thread length, it will be count as 1 conversation). so if senderid = 1, reeiver id =2 and in the next row senderid = 2 and reciever id =1 this is one conversation (till the end of time) Im really stock and not sure how to proceed.

Thanks!

You can use the functions LEAST() and GREATEST() to create unique combinations of the 2 ids and aggregate:

SELECT COUNT(DISTINCT LEAST(m1.senderid, m1.receiverid), GREATEST(m1.senderid, m1.receiverid)) counter
FROM Messages m1
WHERE EXISTS (SELECT 1 FROM Messages m2 WHERE (m2.receiverid, m2.senderid) = (m1.senderid, m1.receiverid))

See the demo .
Results (for your sample data):

counter
2

Here's one option using a self join with least and greatest to get your desired results:

select count(*)
from (
    select distinct least(m1.senderid, m2.senderid), greatest(m1.receiverid, m2.receiverid)
    from messages m1
        join messages m2 on m1.senderid = m2.receiverid and m1.receiverid = m2.senderid
) t

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