2017-02-22 14 views
0

私は輸送データを扱っています。SQL Serverで欠落しているルートを見つけよう

Origin Destination (... other columns) 
CityA CityB 
CityA CityC 

私は、次の募集出会い行方不明の起源先のペアを知りたい:私たちはCityA(原点)がある場合は

  1. を - (> CITYB(宛先)を、私たちはCITYBを持っていません起点)→都市A(目的地)、次に都市B(起点)→都市A(目的地)を選択します。
  2. CityB(送信元) - > CityB(送信先)があり、CityB(送信元) - > CityA(送信先)の場合、何も出力しません。

サンプルintput:

Origin Destination (... other columns) 
CityA CityB 
CityA CityC 

出力例:

Origin Destination (... other columns) 
    CityB CityA 
    CityC CityA 

私が試したもの:

with t1 as (
select distinct t.ofips, t.dfips 
from table t 
), 

t2 as (
select distinct t.ofips, t.dfips 
from table t 
), 

t3 as (
select distinct t1.ofips, t1.dfips 
from t1 
inner join t2 
on t1.ofips = t2.dfips 
and t1.dfips = t2.ofips 
), 

t4 as (
select distinct t1.ofips, t1.dfips 
from t1 
left join t3 
on t1.ofips = t3.ofips 
and t1.dfips = t3.dfips 
where t3.ofips is null or t3.dfips is null 
)--, 
select * from t4 

しかし、結果が間違っているようです。コードの何が間違っていますか?何か不足していますか?

注:テーブルがかなり大きいため、パフォーマンスが問題になります。

答えて

1

あなたはNOT EXISTS使用することができます。これについて

SELECT 
    t1.dfips AS Origin, 
    t1.ofips AS Destination 
FROM t t1 
WHERE NOT EXISTS(
    SELECT 1 
    FROM t t2 
    WHERE 
     t2.ofips = t1.dfips 
     AND t2.dfips = t1.ofips 
); 

ONLINE DEMO

1

どのように?

select t.destination as origin, t.origin as destination 
from t 
where not exists (select 1 
        from t t2 
        where t2.origin = t.destination and t2.destination = t.origin 
       ); 

私はあなたのクエリが何をしているのか分かりませんが、あまりにも複雑すぎるようです。

関連する問題