简体   繁体   English

查找column1与column2匹配的行(可能在另一行中)

[英]Find rows where column1 matches column2 (possibly in an another row)

Say I have some code below from a table called Table1. 说我下面的表Table1中有一些代码。

Column1   | Column2
41391175  | 41000
41523664  | 41523
110505116 | 110509
110453629 | 110505
41000     | 351592

Column1 and Column2 are NVARCHAR(10) . Column1和Column2是NVARCHAR(10) What I want to return is all entries in Column 1 where Column2 is IN Column1, so I want a result to look like this- 我要返回的是列1中的所有条目,其中列2在IN列1中,所以我希望结果看起来像这样-

Column1
41523664
110505116
41000

Right now, this is what my code would look like- 现在,这就是我的代码的样子-

SELECT Column1
FROM Table1
INTERSECT  
SELECT Column2
FROM Table1 ;  

But as of right now, that only finds the EXACT same number as in Column2, rather than one that Column1 contains inside it, so I would just get this result- 但是从现在开始,它只能找到与Column2中完全相同的数字,而不是Column1包含在其中的数字,所以我只会得到以下结果:

Column1

41000

Is there a way to work around this, or to get an IN clause within INTERSECT? 有没有办法解决此问题,或者在INTERSECT中获得IN子句? I haven't been able to find something that does that after some research. 经过研究后,我一直找不到能做到这一点的东西。

I suppose you can match them using LIKE operator: 我想您可以使用LIKE运算符来匹配它们:

SELECT Column1
FROM Table1 AS t
WHERE EXISTS (
    SELECT 1
    FROM Table1 AS x
    WHERE t.Column1 LIKE x.Column2 + '%'
)

Demo on DB Fiddle DB Fiddle上的演示

select c1.column1 from table1 c1 inner join (select distinct column2 from table1) c2 on charindex(c2.column2, c1.column1) = 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM