如何比较两列并在新列中显示差异-SQL Server
我想比较两个nvarchar类型的列,并在一个新列中显示输出,有没有办法在Microsoft SQL Server中实现这一点 例如:如何比较两列并在新列中显示差异-SQL Server,sql,sql-server,Sql,Sql Server,我想比较两个nvarchar类型的列,并在一个新列中显示输出,有没有办法在Microsoft SQL Server中实现这一点 例如: COL1 COL2 -------------------- ----------------------------------- This is my test case This is not my test C
COL1 COL2
-------------------- -----------------------------------
This is my test case This is not my test Case, leave me alone
OUTPUT
---------------------
not, leave me alone
下面的解决方案是单向的:
col1
从col2
中删除单词
样本数据
create table test
(
id int,
col1 nvarchar(max),
col2 nvarchar(max)
);
insert into test (id, col1, col2) values
(1, 'This is my test case', 'This is not my test Case, leave me alone');
解决方案
with cte as
(
select t.id,
replace(s.value, ',', '') as word
from test t
cross apply string_split(t.col2, ' ') s
except
select t.id,
replace(s.value, ',', '')
from test t
cross apply string_split(t.col1, ' ') s
)
select string_agg(c.word, ' ') as result
from cte c
group by c.id;
结果
result
------------------
alone leave me not
result
------------------
not leave me alone
以中间结果查看正在运行的事物
新解决方案
with cte as
(
select t.id,
replace(s.value, ',', '') as word
from test t
cross apply string_split(t.col2, ' ') s
except
select t.id,
replace(s.value, ',', '')
from test t
cross apply string_split(t.col1, ' ') s
)
select string_agg(c.word, ' ') as result
from cte c
group by c.id;
也许这个版本看起来不那么干净,但它应该保留词序
with cte as
(
select t.id,
row_number() over(order by (select null)) as sort,
replace(s.value, ',', '') as word
from test t
cross apply string_split(t.col2, ' ') s
where not exists ( select 'x'
from test t
cross apply string_split(t.col1, ' ') s2
where replace(s2.value, ',', '') = replace(s.value, ',', '') )
)
select string_agg(c.word, ' ') within group (order by c.sort) as result
from cte c
group by c.id;
新结果
result
------------------
alone leave me not
result
------------------
not leave me alone
.“显示差异”是对您尝试执行的操作的非常模糊的描述。例如,如果它会说“这不是我的测试…”怎么办。请写出正确的描述,以及您迄今为止尝试的内容。SQL Server没有数据类型
CLOB
。。。。您在这里使用的实际数据类型是什么?这是否回答了您的问题?Oracle的CLOB
类型等同于T-SQL的NVARCHAR(MAX)
类型。除此之外,我发现这个例子令人困惑。您是单独比较单词还是从左到右从COL2
中“减去”COL1
(输出是否必须按原始顺序)?大写字母是否重要(case
case
)以及为什么my
会出现在预期输出中(me
my
)?一种解决方案是将col1
和col2
值拆分为具有string\u split()
的单独单词,但这会产生case
和case,
不会被排除在同一单词之外。然而,,
必须是结果的一部分。。。另一种方法是从左到右解析col1
和col2
值,并按照出现的顺序删除任何公共字符,case
+case,
将生成,
但abcz-def
将生成z
。。。您真的需要结果中的,
吗?谢谢Sander,是否可以按照COL2中显示的顺序检索结果?比如“别让我一个人呆着”的答案更新了一个新版本,保持了词序。