简体   繁体   中英

Group by two column with vice versa value

I have tried to group by with two columns:

SELECT recipient_id, sender_id, count(*) FROM messengers WHERE recipient_id=41 OR sender_id=41 group by recipient_id, sender_id 

The output will be as shown below:

在此输入图像描述

How I can combine row 1 and row 2 as a row because recipient_id and sender_id have same value which is 40 and 41.

One trick you can use here is to GROUP BY the smaller of the two ID columns and the greater of the two ID columns:

SELECT LEAST(recipient_id, sender_id), GREATEST(recipient_id, sender_id), COUNT(*)
FROM messengers
WHERE recipient_id = 41 OR sender_id = 41
GROUP BY LEAST(recipient_id, sender_id), GREATEST(recipient_id, sender_id)

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