我已經添加了邏輯,如果沒有數值,那麼任何第一支樂隊會在輸出:
DECLARE @t TABLE
(
EmpNo INT ,
payband NVARCHAR(MAX) ,
ContractType NVARCHAR(MAX)
)
INSERT INTO @t
VALUES (123, 'band 4', 'permanent'),
(124, 'band 4', 'contract'),
(125, 'band 3', 'permanent'),
(125, 'band 4 review body', 'permanent'),
(128, 'band', 'permanent');
WITH cte1
AS (SELECT EmpNo ,
payband ,
ContractType ,
PATINDEX('%[0-9]%', payband) AS pi ,
CHARINDEX(' ', payband, PATINDEX('%[0-9]%', payband)) AS ci
FROM @t
WHERE ContractType = 'permanent'
),
cte2
AS (SELECT * ,
ROW_NUMBER() OVER (PARTITION BY EmpNo ORDER BY CASE
WHEN pi > 0
THEN CAST(SUBSTRING(payband,
pi, ABS(pi - ci)) AS INT)
ELSE 0
END DESC) AS rn
FROM cte1
)
SELECT EmpNo ,
payband ,
ContractType
FROM cte2
WHERE rn = 1
輸出:
EmpNo payband ContractType
123 band 4 permanent
125 band 4 review body permanent
128 band permanent
發佈你想要的輸出? – mohan111 2015-04-02 08:57:22
@ mohan111,已更新謝謝 – GK1960 2015-04-02 08:59:40
我的查詢顯示任何結果給你或任何需要的修改 – mohan111 2015-04-02 09:17:02