我在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
如果你交换源和目标,并从以前的任何一行匹配,然后将其删除。
一种方法是使用union all
和not 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
);
另一种选择与排序的来源和目的地重复交易:
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;
您可以使用联盟和比较
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
请尝试查询:
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)