我有一個簡單的要求!我收到“多余”資訊作為文本欄位。它將具有“每年 100 英鎊”、“每種情況 225 英鎊”、“每次事故 105 英鎊”等值……我需要將此欄位中的超額金額加載到目標表的三個欄位中。
對于保單,“P001”可能有 3 種不同型別的超額金額,例如“ExcessPerYear”、“ExcessPerCondition”和“ExcessPerAccident”。根據源資料,我需要決定在哪里加載多余的金額。
CREATE TABLE #SourceData
(Excess VARCHAR(200))
INSERT INTO #SourceData
VALUES
('£500 Per Year'),
('£50 Per Condition Per Year'),
('£450 Per Condition'),
('£200 Per Accident'),
('£100 Per Accident Per Year')
Select * From #SourceData
| 過量的 |
|---|
| 每年 500 英鎊 |
| 每年每條件 50 英鎊 |
| 每條件 450 英鎊 |
| 每次事故 200 英鎊 |
| 每年每次事故 100 英鎊 |
我希望輸出如下
| 過量的 | 每年超額 | 每次事故超額 | 超額條件 |
|---|---|---|---|
| 每年 500 英鎊 | 500 | 無效的 | 無效的 |
| 每年每條件 50 英鎊 | 無效的 | 無效的 | 50 |
| 每條件 450 英鎊 | 無效的 | 無效的 | 450 |
| 每次事故 200 英鎊 | 無效的 | 200 | 無效的 |
| 每年每次事故 100 英鎊 | 無效的 | 100 | 無效的 |
所以基本上,只要超額有一個像“Per Year”這樣的字串,那么金額應該映射到“ExcessPerYear”欄位。如果字串具有“每年按條件”或“按條件”之類的值,則應將超額金額加載到“ExcessPerCondition”表中,最后如果文本類似于“按事故”或“每年按事故”,則應加載到“ExcessPerAccident”欄位中。
我寫了以下代碼。它給了我預期的結果,但是我想問社區是否有更好的撰寫代碼的方法?
我正在使用 SQL Server 2019 標準版。
;WITH GetAllElements
AS
(
SELECT
Excess
,PATINDEX('%[A-Z][a-z]%',Excess) AS Pos_FirstStr
,LEN(Excess) AS LenOfStr
,SUBSTRING(Excess,PATINDEX('%[A-Z][a-z]%',Excess),LEN(Excess)) AS Strng
,PATINDEX('%[0-9]%',Excess) AS Pos_FirstNum
,PATINDEX('%[^0-9]%',REPLACE(Excess,'£','')) AS Pos_LastNum
,TRIM(SUBSTRING(Excess,PATINDEX('%[0-9]%',Excess),PATINDEX('%[^0-9]%',REPLACE(Excess,'£','')))) AS ExcessAmount
FROM #SourceData SD
)
SELECT
Excess
,CASE WHEN Strng='Per Year' THEN ExcessAmount ELSE NULL END AS ExcessPerYear
,CASE WHEN Strng IN ('Per Accident','Per Accident Per Year') THEN ExcessAmount ELSE NULL END AS ExcessPerAccident
,CASE WHEN Strng IN ('Per Condition Per Year','Per Condition') THEN ExcessAmount ELSE NULL END AS ExcessPerCondition
FROM GetAllElements
我知道我不需要 CTE。我認為我需要的只是這 3 個案例陳述,但我撰寫 CTE 只是為了使代碼看起來干凈且易于所有人理解。
uj5u.com熱心網友回復:
只是一個使用 CROSS APPLY 為 CASE 的結果設定別名的選項
Select Excess
,PerYear = case when Class='PY' then value end
,PerAccident = case when Class='PA' then value end
,PerCondidtion = case when Class='PC' then value end
From #SourceData A
Cross Apply ( values ( case when charindex('Per Accident' ,Excess)>0 then 'PA'
when charindex('Per Condition',Excess)>0 then 'PC'
when charindex('Per Year' ,Excess)>0 then 'PY' end
, try_convert(money,left(Excess,charindex(' ',Excess ' ')))
)
) B(Class,Value)
結果

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/528478.html
