我的ID字符串在数据库中具有这些值,如下所示:
My_ID_String
=============
ABC123
123
ABC456
798
我的最终目标是替换所有没有前缀的ABC。但是我遇到的挑战是该列必须具有唯一值。我有解决这个问题的计划。但是,我要完成的工作是,如果我删除前缀不适当,则找出具有重复项的重复项。换句话说,我希望查询返回ABC456的结果,但不返回ABC123的结果,因为如果执行替换功能,这将导致重复。
预期结果:
My_ID_String
============
ABC456
答案 0 :(得分:1)
另一个选择
示例
;with cte as (
Select Top 1 with ties *
From YourTable
Order By sum(1) over (partition by replace(My_ID_String,'ABC','') )
)
Select *
From cte
Where My_ID_String like 'ABC%'
返回
My_ID_String
ABC456
答案 1 :(得分:0)
您可以使用:
SELECT My_Id_String AS MyIdString
FROM tab
WHERE My_Id_String LIKE 'ABC%'
EXCEPT
SELECT 'ABC' + My_Id_String
FROM tab
WHERE My_Id_String NOT LIKE 'ABC%'
答案 2 :(得分:0)
那是你想做什么
WITH StrTable AS
(
SELECT 'ABC123' My_ID_String
UNION
SELECT '12355555'
UNION
SELECT 'ABC456'
UNION
SELECT NULL
UNION
SELECT 'DEF123'
UNION
SELECT 'DEF456'
UNION
SELECT 'GHI123'
UNION
SELECT 'GHI456'
UNION
SELECT 'GHI789'
)
SELECT CONCAT( LEFT(My_ID_String, 3),
MAX(REPLACE(My_ID_String, LEFT(My_ID_String, 3), ''))
) Result
FROM StrTable
WHERE TRY_CAST(LEFT(My_ID_String, 3) AS INT) IS NULL
AND My_ID_String IS NOT NULL
GROUP BY LEFT(My_ID_String, 3);
返回:
+--------+
| Result |
+--------+
| ABC456 |
| DEF456 |
| GHI789 |
+--------+
答案 3 :(得分:0)
由于这似乎是最终目标,因此可以在一个步骤中完成所有这两个操作,从而获得所有不同的值。消除重复项时,只需获取所需的独特值即可。您可能正在寻找类似这样的东西。
declare @Something table
(
My_ID_String varchar(50)
)
insert @Something values
('ABC123')
, ('123')
, ('ABC456')
, ('798')
select case when count(replace(s.My_ID_String, 'ABC', '')) = 1 then max(s.My_ID_String) else max(replace(s.My_ID_String, 'ABC', '')) end
from @Something s
group by replace(s.My_ID_String, 'ABC', '')