我有一个
的数据集[TELEPHONE1] [TELEPHONE2] [TELEPHONE3]
NULL 75471512454 1254875421
125454547 NULL 7465457112
NULL NULL 7457512124
我想将其提取为两列
[MOBILE] [HOME]
75471512454 1254875421
7465457112 1254545471
7457512124 NULL
[手机]将是以' 7'开头的任何数字。 [Home]将是以任何其他内容开头的任何数字
我认为Coalesce函数会获得第一个非null值..但有没有办法让它获取包含给定字符/数字的第一个非null值?
非常感谢
答案 0 :(得分:1)
您可以使用case
这样的表达式:
select
Mobile = case
when left(Telephone1,1)='7' then Telephone1
when left(Telephone2,1)='7' then Telephone2
when left(Telephone3,1)='7' then Telephone3
else null
end
, Home = case
when left(Telephone1,1)='7' then coalesce(Telephone2,Telephone3)
when left(Telephone2,1)='7' then coalesce(Telephone1,Telephone3)
when left(Telephone3,1)='7' then coalesce(Telephone1,Telephone2)
else null
end
from t
rextester演示:http://rextester.com/AOWK37324
返回:
+-------------+------------+
| Mobile | Home |
+-------------+------------+
| 75471512454 | 1254875421 |
| 7465457112 | 125454547 |
| 7457512124 | NULL |
+-------------+------------+
答案 1 :(得分:0)
COALESCE
只是多个case when
,所以您可以将内部逻辑修改为:
case when TELEPHONE1 like '7%' THEN TELEPHONE1
when TELEPHONE2 like '7%' THEN TELEPHONE2
when TELEPHONE3 like '7%' THEN TELEPHONE3
else NULL
end as MOBILE,
case when ISNUMERIC(TELEPHONE1) =1 AND TELEPHONE1 not like '7%' THEN TELEPHONE1
when ISNUMERIC(TELEPHONE2) =1 AND TELEPHONE2 not like '7%' THEN TELEPHONE2
when ISNUMERIC(TELEPHONE3) =1 AND TELEPHONE3 not like '7%' THEN TELEPHONE3
else NULL
end as HOME