删除重复的来源到目的地(例如,对于2个不同的条目(行),从德里到孟买,从孟买到德里,输出应为一个)

时间:2019-02-05 11:35:36

标签: sql sql-server database

我在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

如果交换“源”和“目标”,并且它与上一行匹配,则将其删除。

4 个答案:

答案 0 :(得分: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 :(得分: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;

答案 2 :(得分: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

答案 3 :(得分: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)