How to remove duplicates within a string from the table in SQL server 2016(如何在SQL Server 2016中将字符串中的重复项从表中删除)
本文介绍了如何在SQL Server 2016中将字符串中的重复项从表中删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我得到了一个包含一列字符串列的表。这些字符串由;
分隔。现在,我想在拆分字符串后删除重复项。例如:
-----------
| w;w;e;e |
-----------
| q;r;r;q |
-----------
| b;n;n;b |
-----------
结果应为:
-------
| w;e |
-------
| q;r |
-------
| b;n |
-------
此外,它不应该是Select
函数,而应该是delete
函数(不是100%确定的)。因此原始表中的值将不再重复。
推荐答案
对于update
语句,这将消除您的列的重复项:
update t
set col = stuff((
select distinct
';'+s.Value
from string_split(t.col,';') as s
for xml path (''), type).value('.','varchar(1024)')
,1,1,'');
在SQL SERVER 2016中,您可以使用string_split()
和stuff()
with select ... for xml path ('')
method of string concatenation仅连接不同的值。
select
t.id
, t.col
, dedup = stuff((
select distinct
';'+s.Value
from string_split(t.col,';') as s
for xml path (''), type).value('.','varchar(1024)')
,1,1,'')
from t
dbfiddle演示:here
rextester demo:http://rextester.com/MAME55141;此demo在string_split()
缺席的情况下使用Jeff Moden的CSV拆分器函数。
退货:
+----+---------+-------+
| id | col | dedup |
+----+---------+-------+
| 1 | w;w;e;e | e;w |
| 2 | q;r;r;q | q;r |
| 3 | b;n;n;b | b;n |
+----+---------+-------+
拆分字符串引用:
- Tally OH! An Improved SQL 8K "CSV Splitter" Function - Jeff Moden
- Splitting Strings : A Follow-Up - Aaron Bertrand
- Split strings the right way – or the next best way - Aaron Bertrand
string_split()
in SQL Server 2016 : Follow-Up #1 - Aaron Bertrand
这篇关于如何在SQL Server 2016中将字符串中的重复项从表中删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:如何在SQL Server 2016中将字符串中的重复项从表中删除


基础教程推荐
猜你喜欢
- 从字符串 TSQL 中获取数字 2021-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- 带更新的 sqlite CTE 2022-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01