如何解决如何在SQL中获得独特的路由?
对于下表(每列的数据类型为varchar):
RouteId R1和R4,德里德里孟买和孟买德里路线将被视为同一条路线。 如何从上表中获得独特的路线? 或创建一个新列,该列的R1和R4值相同
预期输出:
解决方法
select t1.route_id,t1.source,t1.destination,t2.route_id as same_route
from your_table t1
left join your_table t2 on t1.source = t2.destination and t1.destination = t2.source
,
您可以使用not exists
获得不同的路线:
select t.*
from mytable t
where not exists (
select 1
from mytable t1
where
t1.source = t.destination
and t1.destination = t.source
and t1.destination > t1.source
)
另一方面,您可以使用dense_rank()
分配路线号;如果您的数据库支持least()
和greatest()
:
select
t.*,dense_rank() over(order by least(source,destination),greatest(source,destination)) rn
from mytable t
,
#tabel_name = city_route
select
Route_id,source,destination,concat('D',dense_rank() over (order by s,d)) distinct_route_id
from (
select c1.*,source s,destination d
from city_route c1
where source > destination
union all
select c2.*,source
from city_route c2
where source < destination
)a
order by len(route_id),route_id
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。