Domanda

I'm trying to write a query that seems pretty basic in the world of connect by queries. But somehow I'm missing one important piece. I want to know for each "source" id what the ultimate "target" id is. For example, I have this source data:

src trg
1   2
2   3
3   4
7   8

My current incarnation (SQL Fiddle) of the query returns the desired values:

select src, connect_by_root trg ult_trg
from t 
connect by nocycle prior src = trg
order by ult_trg, src;

The problem is that it also returns undesired values. My desired output is this:

1, 4
2, 4
3, 4
7, 8

What is the missing idea I need to limit my result set to the desired rows?

È stato utile?

Soluzione

select 
  connect_by_root src as src,
  trg ult_trg
from t 
where 
  connect_by_isleaf = 1
  connect by nocycle src = prior trg
order by ult_trg, src

Altri suggerimenti

select src, MAX(connect_by_root trg) ult_trg
from t 
connect by nocycle prior src = trg
GROUP BY src
order by ult_trg, src;

Modified Fiddle

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top