如果您只有两列,这很容易:
select distinct least(col1, col2), greatest(col1, col2)
from t;
有了三个,这有点难:
select distinct least(no1, no2, no3) as smallest,
(case when no1 not in (least(no1, no2, no3), greatest(no1, no2, no3)) then no1
when no2 not in (least(no1, no2, no3), greatest(no1, no2, no3)) then no2
else no3
end) as middle,
greatest(no1, no2, no3) as biggest
from items;
请注意,这distinct
是获取不同组的更简洁的方法。
编辑:
如果您想对更多列执行此操作,MySQL 不提供该nth()
功能(类似于least()
and greatest()
。您可以执行以下操作。取消透视值(假设每行都有一个 id),然后使用group_concat()
选项order by
:
select distinct nos
from (select id, group_concat(noi order by noi) as nos
from (select id,
(case when n.n = 1 then no1
when n.n = 2 then no2
when n.n = 3 then no3
end) as noi
from items i cross join
(select 1 as n union all select 2 union all select 3) n
) nn
group by id
) nn;
这会将值作为逗号分隔列表返回。