Fromjourney ToJourney KM
Delhi Mumbai 1000
Mumbai Delhi 1000
Gurgaon Noida 50
Noida Gurgaon 50
Ghaziabad Faridabad 60
Faridabad Ghaziabad 60
Delhi Meerut 80
Meerut Delhi 80
我有三列from
,To
和KM
。
当From To拥有相同的城市时,我想要单行数据 像From-Mumbai,To-Delhi To-Delhi,From-Mumbai
Ι想要这一行的单行
答案 0 :(得分:1)
select T1.Fromjourney,T1.ToJourney
,T2.*
from TestTable T1
left join TestTable T2
on T1.Fromjourney = T2.ToJourney
and T1.ToJourney = T2.Fromjourney
and T1.Fromjourney < T2.Fromjourney
where T2.Fromjourney is not null
| Fromjourney | ToJourney | Fromjourney | ToJourney | KM |
|-------------|-----------|-------------|-----------|------|
| Delhi | Mumbai | Mumbai | Delhi | 1000 |
| Gurgaon | Noida | Noida | Gurgaon | 50 |
| Faridabad | Ghaziabad | Ghaziabad | Faridabad | 60 |
| Delhi | Meerut | Meerut | Delhi | 80 |
答案 1 :(得分:0)
我会这样做:
select t.*
from testtable t
where Fromjourney < ToJourney
union all
select t.*
from testtable t
where Fromjourney > ToJourney and
not exists (select 1
from testtable t2
where t2.Fromjourney = t.ToJourney and t2.ToJourney = t.Fromjourney);