I have a table:
id a b
1 1 2
2 2 1
3 2 1
4 3 2
5 2 3
col a b [1 2] is equal to col a b [2 1], so i'd like these data into a group, how can i get a result something looks like:
id a b
5 2 3
3 2 1
Thanks.
你可以做:
select max(id), least(a, b) as a, greatest(a, b) as b
from t
group by least(a, b), greatest(a, b);
(1, 2)
如果可以的话,这实际上会(2, 3)
为您的数据生成值。
如果要按原始顺序获取数据,则可以将上述内容用作子查询并加入 id:
select t.*
from t join
(select max(id) as maxid, least(a, b) as a, greatest(a, b) as b
from t
group by least(a, b), greatest(a, b)
) tmax
t.id = tmax.maxid;
SELECT *
FROM TableName
WHERE (LEAST(a, b), GREATEST(a, b), id) in
(
SELECT LEAST(a, b) as x,
GREATEST(a, b) as y,
MAX(ID) as id
FROM TableName
GROUP BY x, y
)