SQL入世对同一个表,但不同的列

问题描述 投票:1回答:2

往来

telephone1     telephone2
---------------------------
+271566681     NULL
+276445884     +271679161
+275684835     NULL
NULL           +276496136

tFormat

operator     range
-------------------
MTN          +2764
Vodacom      +2716

预期成绩

TELEPHONE1     OPERATOR     TELEPHONE2     OPERATOR
---------------------------------------------------
+271666681     Vodacom      NULL           NULL
++276445884    MTN          +271679161     Vodacom
 NULL          NULL         +276496136     MTN

目前的结果

TELEPHONE1     OPERATOR     TELEPHONE2     OPERATOR
---------------------------------------------------
+271666681     Vodacom      NULL           NULL
+276445884     MTN          +271679161     NULL
 NULL          NULL         +276496136     NULL

查询显示的电话号码和运营商为T1,但只显示电话号码,而不是运营商T2。有两个表之间没有关系

select    
    c.telephon1, t1.operator
    c.telephone2, t2.operator
from
    Contacts as c 
left join 
    tFormat as t1 on left(c.telephone1, 5) = t1.range
left join 
    tFormat as t2 on left(c.telephone2, 5) = t2.NUMBER_RANGE
sql join trim
2个回答
1
投票

下面是你所提供的测试数据结果,查询是一样的你和我已经加入NVL子句中的连接条件,因为都为空的电话号码。

with t1 as
(
select '+271566681' as telephone1, null as telephone2 from dual
union
select '+276445884' as telephone1, '+271679161' as telephone2 from dual
union
select '+275684835' as telephone1, NULL as telephone2 from dual
union
select NULL as telephone1, '+276496136' as telephone2 from dual
)
,t2 as 
(
select 'MTN' as opetr, '+2764' as rnge from dual
union
select 'Vodacom' as opetr, '+2716' as rnge from dual
)

select
t1.telephone1, t22.opetr,
t1.telephone2, t23.opetr
from t1 
left outer join t2 t22 on substr(nvl(t1.telephone1, '00000'),1,5) = t22.rnge
left outer join t2 t23 on substr(nvl(t1.telephone2, '00000'),1,5) = t23.rnge;

NULL    NULL    +276496136  MTN
+276445884  MTN +271679161  Vodacom
+271566681  NULL    NULL    NULL
+275684835  NULL    NULL    NULL

Your query would be -
    select
    t1.telephone1, t22.operator,
    t1.telephone2, t23.operator
    from Contacts t1 
    left outer join tFormat t22 on substr(nvl(t1.telephone1, '00000'),1,5) = t22.range
    left outer join tFormat t23 on substr(nvl(t1.telephone2, '00000'),1,5) = t23.range;

Note - There are issue with the test data which you have provided
> Table has 4 records but output has 3 records
> we don't have telephone1 number starting with +2716, but your output has one
> There is record in output which starts with ++, which is not there in your test data.

0
投票

我想你想:

select c.telephone1, t1.operator,
       c.telephone2, t2.operator
from Contacts  c left join 
     tFormat t1
     on left(c.telephone1, 5) = t1.range left join 
     tFormat t2
     on left(c.telephone2, 5) = t2.range
where t1.range is not null or t2.range is not null;

Here是分贝<>拨弄。

© www.soinside.com 2019 - 2024. All rights reserved.