Sql 多列检索单个值

Sql multiple columns to retrieve a single value

id Mobile   Home      Business
1  07707    0161      abcdefg
2  Null   07798567     Null
3  07709  078 iju      Null

你好。我想弄清楚如何从 table 中检索手机号码,其中有一些错误数据。

数字可以在任何列中,这些列都是varchars。 求号必须以07开头,长度必须是11位

到目前为止,我只做到了这一点:

select REPLACE ( 
      COALESCE (Business_Phone, Cell_Phone, Home_Phone) Contact_Phone 
               , ' '.'') 
from testtable
where len () =11?

如有任何建议,我们将不胜感激。谢谢

试试这个查询:

SELECT * FROM (
    SELECT CASE
        WHEN REPLACE(Business_Phone, ' ', '') LIKE '07[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]' THEN REPLACE(Business_Phone, ' ', '')
        WHEN REPLACE(Cell_Phone, ' ', '') LIKE '07[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]' THEN REPLACE(Cell_Phone, ' ', '')
        WHEN REPLACE(Home_Phone, ' ', '') LIKE '07[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]' THEN REPLACE(Home_Phone, ' ', '')
        END AS TrueMobile
    FROM testtable
) x
WHERE x.TrueMobile IS NOT NULL

它试图找到一个包含 11 位数字(前两位为 07)、中间任意数量的空格且没有其他字符的字段。它首先尝试 Business_Phone,然后 Cell_Phone,然后 Home_Phone。这 3 个字段中 none 匹配的记录从结果集中排除。

测试数据

DECLARE @TABLE TABLE (id INT, Mobile VARCHAR(20), Home VARCHAR(20),Business VARCHAR(20))
INSERT INTO @TABLE VALUES 
(1,'07707'      ,    '0161'  , 'abcdefg'),
(2,Null         ,  '07798567',     Null),
(3,'07709'      ,  '078 iju' ,  '07709175555'),
(4,'07709178921',  '078 iju' ,     Null)

查询

;WITH CTE AS 
(
    SELECT * 
    FROM @TABLE 
     UNPIVOT (Numbers FOR Num_Types IN (Mobile,Home,Business)) up
)
SELECT *
FROM CTE C1
WHERE NOT EXISTS(SELECT 1 
                 FROM CTE C2
                 WHERE LEFT(C2.Numbers, 2) = '07'
                 AND C2.Numbers NOT LIKE '%[^0-9]%'
                 AND C1.id = C2.id
                 AND C1.Numbers = C2.Numbers
                 AND C1.Num_Types = C2.Num_Types)

结果

╔════╦═════════╦═══════════╗
║ id ║ Numbers ║ Num_Types ║
╠════╬═════════╬═══════════╣
║  1 ║ 0161    ║ Home      ║
║  1 ║ abcdefg ║ Business  ║
║  3 ║ 078 iju ║ Home      ║
║  4 ║ 078 iju ║ Home      ║
╚════╩═════════╩═══════════╝