1
我有两个NVARCHAR列的表:源和目标。如何找到部分重复?
我想查找可以找到具有相同源的另一行和包含当前源的目标的行。
在下面的例子中,我想找到行1和7:
- 行1是 “部分重复” 行3的
- 行图7是第6行的 “部分重复”
下面是SQL代码片段:
CREATE TABLE #YourTable (ID int, [source] nvarCHAR(12), [target] nvarCHAR(12))
INSERT INTO #YourTable ([ID],[source],[target]) VALUES (1,'wordA','word1')
INSERT INTO #YourTable ([ID],[source],[target]) VALUES (2,'wordA','word2')
INSERT INTO #YourTable ([ID],[source],[target]) VALUES (3,'wordA','word3 ; word1')
INSERT INTO #YourTable ([ID],[source],[target]) VALUES (4,'wordB','word4')
INSERT INTO #YourTable ([ID],[source],[target]) VALUES (5,'wordC','word5')
INSERT INTO #YourTable ([ID],[source],[target]) VALUES (6,'wordD','word6 ; word7')
INSERT INTO #YourTable ([ID],[source],[target]) VALUES (7,'wordD','word7')
SELECT
[source],
STUFF((
SELECT ', ' + [target]
FROM #YourTable
WHERE ([source] = Results.[source])
FOR XML PATH (''))
,1,2,'') AS NameValues
FROM #YourTable Results
GROUP BY [source]
HAVING COUNT(1)>1
DROP TABLE #YourTable
我的第一个想法是串联但它并没有让我更接近解决方案...
我可以将我的数据导出为CSV并使用编程语言(python,C#,...)来隔离这些ID,但我很好奇看看它如何在SQL中完成。
最终目标是消除“部分重复”。
我改变了'和t2.target像t1.target || '%'到'和(t2。[target] like'%'+ t1。[target] +'%'或t2。[target] like t1。[target] +'%'或t2。[target] like '%'+ t1。[target])'。 –
'和[t2。[target] like'%'+ t1。[target] +'%''就足够了,因为''%'匹配空字符串(这就是让'和t2.target <>在where子句中的t1.target') – collapsar