我有一個值需要決議為可能的三個值:
| 主機 | 單元1 | 單元2 | 第三單元 |
|---|---|---|---|
| 10ABC | 10A | 10B | 10℃ |
| 10AB | 10A | 10B | 無效的 |
我在下面的腳本中完成了我需要的。我的問題是……是否有更好、更有效的方法(代碼行更少)?
cast([UnitNum] as char(5)) as MasterUnit,
left(cast([UnitNum] as char(5)), 3) as Unit1,
case
when (left(left(cast([UnitNum] as char(5)), 2) right(cast([UnitNum] as char(5)), 2),3)) = left(cast([UnitNum] as char(5)), 2)
then NULL
else (left(left(cast([UnitNum] as char(5)), 2) right(cast([UnitNum] as char(5)), 2),3))
end as Unit2,
case
when (left(cast([UnitNum] as char(5)), 2)) (right(cast([UnitNum] as char(5)), 1)) = left([UnitNum],2)
then NULL
else (left(cast([UnitNum] as char(5)), 2) right(cast([UnitNum] as char(5)), 1))
end as Unit3
uj5u.com熱心網友回復:
通過一些字串操作和CROSS APPLY
Select A.*
,Unit1 = S1 nullif(substring(S2,1,1),'')
,Unit2 = S1 nullif(substring(S2,2,1),'')
,Unit3 = S1 nullif(substring(S2,3,1),'')
From YourTable A
Cross Apply ( values ( left(MasterUnit,patindex('%[^0-9]%',MasterUnit)-1),substring(MasterUnit,patindex('%[^0-9]%',MasterUnit),100) ) ) B(S1,S2)
結果

uj5u.com熱心網友回復:
對您的樣本資料做出一些假設,也許像下面這樣使用交叉應用來重復使用最初的兩個字符是盡可能少的:
select MasterUnit,
u NullIf(Substring(MasterUnit,3,1),'') Unit1,
u NullIf(substring(MasterUnit,4,1),'') Unit2,
u NullIf(substring(MasterUnit,5,1),'') Unit3
from t
cross apply(values(Left(MasterUnit,2)))m(u);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/534877.html
標籤:数据库表
上一篇:今年的WTD與去年的WTD相比
