SQL比较同一表中的值行

SQL比较同一表中的值行,sql,sql-server,Sql,Sql Server,我有一个数据库,我需要搜索双重登录 类型:Char 例如: 15-Abc 15-Deg 17-Abc 我需要找到像15/17 Abc,双重登录,但不同的第一位数字的用户 如何搜索登录名? 我有几千个嗯。您可以使用exists查找第二部分的匹配项。一种方法是拆分字符串。另一种方法是仅使用字符串操纵函数: select t.* from t where login like '%-%' and exists (select 1 from t t2

我有一个数据库,我需要搜索双重登录

类型:Char

例如:

15-Abc 
15-Deg
17-Abc 
我需要找到像15/17 Abc,双重登录,但不同的第一位数字的用户 如何搜索登录名? 我有几千个

嗯。您可以使用exists查找第二部分的匹配项。一种方法是拆分字符串。另一种方法是仅使用字符串操纵函数:

select t.*
from t
where login like '%-%' and
      exists (select 1
              from t t2
              where t2.login <> t.login and
                    t2.login like '%-%' and
                    substring(t2.login, charindex('-', t2.login), len(t2.login)) = substring(t.login, charindex('-', t.login), len(t.login))
             );

这样,您可以找到所有重复的零件:

declare @t table (col varchar(100));
insert into @t values
('15-Abc'),
('15-Deg'),
('17-Abc');

select substring(col, 3, len(col))
from @t
group by substring(col, 3, len(col))
having count(*) > 1;
如果需要原始表的行,请使用以下代码:

declare @t table (col varchar(100));
insert into @t values
('15-Abc'),
('15-Deg'),
('17-Abc');

with cte as
(
select substring(col, 3, len(col)) as same_part
from @t
group by substring(col, 3, len(col))
having count(*) > 1
)

select *
from @t t
where  exists(select * from cte c where substring(t.col, 3, len(col)) = c.same_part);

格式总是两个数字,一个破折号,然后是三个字母吗?可能是