SQL Server:从结果集中删除子字符串结果

时间:2018-09-23 02:33:28

标签: sql-server tsql

Please help with the query

请帮助进行T-SQL查询

假设表中的数据如下所示

| ID  | Name | FullName |
|  1  | a    | a        |
|  2  | b    | ab       |
|  3  | c    | abc      |
|  4  | d    | ad       |
|  5  | e    | ade      |
|  6  | i    | i        |
|  7  | g    | ig       |

我想得到如下结果集

| ID | Name | FullName |
| 3  | c    | abc      | 
| 5  | e    | ade      |
| 7  | g    | ig       |

1 个答案:

答案 0 :(得分:0)

要检查子字符串,可以使用内置的CHARINDEX函数。子查询查找子字符串与其他任何行都匹配的任何行。然后从最终结果集中过滤掉这些ID。

create table #example (
    Id int, [Name] varchar(255), [FullName] varchar(255)
);
go

insert into #example (Id, Name, FullName)
values
(1, 'a', 'a'),
(2, 'b', 'ab'),
(3, 'c', 'abc'),
(4, 'd', 'ad'),
(5, 'e', 'ade'),
(6, 'i', 'i'),
(7, 'g', 'ig');
go



select *
from #example as a where a.Id not in (
    select distinct
        a.Id
    from
        #example as a
        inner join #example as b
        on a.Id <> b.Id -- don't check against yourself
        and charindex(a.FullName, b.FullName, 0) > 0 -- if charindex > 0 then there is a substring match
)
相关问题