多列上的“对称”GROUP BY

时间:2016-06-07 08:34:45

标签: sql group-by symmetric

我有一张这样的表:

_id sender_id receiver_id text
1   1         2           xxx
2   2         1           yyy
3   1         2           xyz
4   3         1           abc

我需要在sender_idreceiver_id列上执行GROUP BY,但它应该是对称的,因此{1,2}和{2,1}应该被认为是相同的基。

此查询可以在随机DBMS上执行,因此它应尽可能最标准。

1 个答案:

答案 0 :(得分:5)

我认为您需要两个 CASE表达式,因为您要对两列进行分组:

GROUP BY CASE WHEN sender_id < receiver_id THEN sender_id
              ELSE receiver_id
         END,
         CASE WHEN sender_id < receiver_id THEN receiver_id
              ELSE sender_id
         END,

如果您使用的是MySQL,请考虑使用LEAST()GREATEST()技巧:

SELECT LEAST(sender_id, receiver_id), GREATEST(sender_id, receiver_id)
FROM yourTable
GROUP BY LEAST(sender_id, receiver_id), GREATEST(sender_id, receiver_id)

在SQLite中,您可以将MAX()MIN()用作scalar functions

SELECT MIN(sender_id, receiver_id), MAX(sender_id, receiver_id)
FROM yourTable
GROUP BY MIN(sender_id, receiver_id), MAX(sender_id, receiver_id)