如何在SQL中获得独特的路由?

问题描述

对于下表(每列的数据类型为varchar):

enter image description here

RouteId R1和R4,德里德里孟买和孟买德里路线将被视为同一条路线。 如何从上表中获得独特的路线? 或创建一个新列,该列的R1和R4值相同

预期输出:

enter image description here

解决方法

        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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...