首页 > 解决方案 > SQL:从不同的表中提取单元格中间的数字

问题描述

我需要帮助从不同的表中提取数字中的数字。我会解释:第一张桌子有电话号码。例子:+12125634533, +41542858585

第二张桌子有

country code | second column
-------------+--------------
1            | usa
41           | switzerland

如何让运营商在数字范围内?

例子:

+12125634533-- 运营商是212(1 是国家代码,5634533 是电话号码 - 始终是 7 个数字)

+41542858585-- 运营商是54(41是国家代码,2858585是电话号码)。

标签: sqlsql-serverssms

解决方案


假设电话前缀是唯一的并且电话号码总是以 开头+,那么是这样的:

select t1.*,
       substring(t1.phonenumber, 2 + len(t2.countrycode),
                 len(t1.phonenumber) - 7 - len(t2.countrycode) - 1
                )
from table1 t1 left join
     table2 t2
     on t1.phonenumber like '+' + t2.countrycode + '%';

是一个 db<>fiddle。


推荐阅读