我需要将一列中的数据截断为 10 个字符。但是,我不能有任何重复项,因此我希望任何重复项以 ~1 作为第一个重复项,以 ~2 作为第二个重复项。这是我所拥有的一个示例:
Column
------
The ABC Company Inc.
The ABC Cooperative
XYZ Associates LLC.
我希望结果是:
Column
------
The ABC ~1
The ABC ~2
XYZ Associ
结尾不一定是~1 或~2,我只需要在截断后让它独一无二。截断后可能有超过 3 或 4 个重复。
到目前为止,我只是手动截断和编辑表格:
update Table set Column = Left(Column, 10) where len(Column) > 10
最佳答案
首先,您关心的是前 8 个字符,而不是前 10 个,因为您需要为额外的数字预留位置。
假设您的重复次数少于 10 次,您可以这样做:
with toupdate as (
select t.*,
row_number() over (partition by left(col, 8) order by (select null)) as seqnum,
count(*) over (partition by left(col, 8) ) as cnt
from t
update toupdate
set col = (case when cnt = 1 then left(col, 10)
else left(col, 8) + '~' + cast(seqnum as char(1));
同样的想法也可以用于select
。
关于sql - T-SQL 截断文本并在末尾添加数字以避免重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38594498/