Sql 以分组匹配col1,col2和col2,col1的方式同时按两列分组
我的“聊天”表中有发件人id、收件人id和消息列:Sql 以分组匹配col1,col2和col2,col1的方式同时按两列分组,sql,postgresql,select,group-by,Sql,Postgresql,Select,Group By,我的“聊天”表中有发件人id、收件人id和消息列: sender_id | recipient_id | message ------------------------------------- 1 | 2 | Test 1 2 | 1 | test test 1 | 3 | more tests 1 | 2 | aaaa 我想将结果分组为(
sender_id | recipient_id | message
-------------------------------------
1 | 2 | Test 1
2 | 1 | test test
1 | 3 | more tests
1 | 2 | aaaa
我想将结果分组为(发件人id、收件人id)和反向分组(收件人id、发件人id)。结果应如下所示:
sender_id | recipient_id
------------------------
1 | 2
1 | 3
这是因为发送者也可以是另一行中的接收者,我不希望出现这样的结果
sender_id | recipient_id
------------------------
1 | 2
2 | 1
这是一种工作正常但几乎没有缺陷的SQL:
SELECT DISTINCT ON sender_id+recipient_id, sender_id, recipient_id
FROM chat
WHERE (sender_id = 10 AND recipient_id = 10);
缺陷:1。我无法在代码中使用DISTINCT ON。2.它将分组成一行(我不确定它是否真的会发生),如下所示:
sender_id | recipient_id
------------------------
10 | 5
9 | 6
我不知道怎么解决这个问题。非常感谢您的帮助。您可以使用least()
和grest()
首先获取较低的ID,最后获取较高的ID(如果您愿意,反之亦然)
具有不同的,
:
SELECT DISTINCT
least(sender_id, recipient_id) least_id,
greatest(sender_id, recipient_id) greatest_id
FROM chat;
或者使用groupby
,如果您确实想要聚合某些内容(无论是什么,max(message)
?):
它是完美的。非常感谢你。
SELECT least(sender_id, recipient_id) least_id,
greatest(sender_id, recipient_id) greatest_id,
...
FROM chat
GROUP BY least(sender_id, recipient_id),
greatest(sender_id, recipient_id);