删除重复的源到目的地(例如,2个不同条目(行),德里孟买和孟买新德里,输出应该是一个)

问题描述 投票:1回答:4

我在SQL Server数据库中的表。

Source     Destination     Fare
-------------------------------
Delhi      Mumbai           100
Mumbai     Delhi            100
London     New York         500

我要写产生以下结果的SQL查询。

Source     Destination     Fare
-------------------------------
Delhi      Mumbai           100
London     New York         500

如果你交换源和目标,并从以前的任何一行匹配,然后将其删除。

sql sql-server database
4个回答
1
投票

一种方法是使用union allnot exists

select source, destination, fare
from t
where source < destination
union all
select source, destination, fare
from t
where source > destination and
      not exists (select 1
                  from t t2
                  where t2.source = t.destination and t2.destination = t.source
                 );

1
投票

另一种选择与排序的来源和目的地重复交易:

WITH cte AS (
    SELECT
        CASE WHEN Source < Destination THEN Source ELSE Destination END AS Source,
        CASE WHEN Source < Destination THEN Destination ELSE Source END AS Destination,
        Fare
    FROM yourTable
)

SELECT DISTINCT Source, Destination, Fare
FROM cte;

1
投票

您可以使用联盟和比较

with cte as    
(
select 'Delhi' as source, 'Mumbai' as destination, 100 as fare
union all
select 'Mumbai' as source, 'Delhi' as destination, 100 as fare
union all
select 'London','New York',500
)   select  source,destination,fare from cte
    where source<destination
    union
    select  source,destination,fare        
    from cte where source<destination

产量

source  destination     fare
Delhi   Mumbai          100
London  New York        500

0
投票

请尝试查询:

select min(Source), max(Destination), Fare 
from 
    tbl 
where Source in (select Destination from tbl) 
group by Fare
union all
select * from 
    tbl 
where Source not in (select Destination from tbl)
© www.soinside.com 2019 - 2024. All rights reserved.