2017-02-22 3 views
0

Ich arbeite an einem Transportdaten.Finden Sie fehlende Route in SQL Server

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

Ich will Quelle-Ziel-Paaren fehlt, um herauszufinden, die folgende Einstellung zu treffen:

  1. Wenn wir Citya (Ursprung) -> CityB (Ziel), aber wir haben nicht CityB (Herkunft) -> StadtA (Zielort), dann Ausgang CityB (Herkunft) -> OrtA (Zielort).
  2. Wenn wir CityA (Ursprung) -> CityB (Ziel) haben und wir CityB (Ursprung) -> CityA (Ziel) haben, dann gib nichts aus.

Probe intput:

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

Beispielausgabe:

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

Was ich versucht:

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 

Doch die Ergebnisse scheinen nicht korrekt. Was stimmt nicht mit dem Code? Fehle ich etwas?

Hinweis: Leistung ist ein Problem, weil die Tabelle ziemlich groß ist.

Antwort

1

können Sie NOT EXISTS verwenden:

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

Wie wäre das?

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 
       ); 

Ich bin nicht sicher, was Ihre Abfrage der Fall ist, aber es scheint, viel zu kompliziert.

Verwandte Themen