如何获取结果集中没有重复单元格的行

时间:2019-10-17 12:11:14

标签: sql-server

我想获得具有唯一值的行: 例如:在第一行name1中包含“ AA”的情况下,我们必须将“ AA”与表中的所有单元格进行比较(如果匹配),则必须删除整行。

i / p结果以下。

   declare @tbl table (ID INT IDENTITY(1,1),Name1 varchar(100),Name2 
   varchar(100),Name3 varchar(100)) 
   insert into @tbl 
   select 'AA' ,'AB','AC'
   UNION ALL
   SELECT 'BA','BB','AA'
   UNION ALL
   SELECT 'CA','CB','CC'
   UNION ALL
   SELECT 'DA','DB','DD'
   UNION ALL
   SELECT 'EA','AB','EC'
   UNION ALL
   SELECT 'CC','FB','FC' 
   SELECT * FROM @tbl

输入:不考虑id列。

ID  Name1   Name2   Name3
1     AA       AB      AC
2     BA       BB      AA
3     CA       CB      CC
4     DA       DB      DD
5     EA       AB      EC
6     CC       FB      FC

预期的结果:

ID  Name1   Name2   Name3
4     DA      DB      DD


declare @tbl table (ID INT IDENTITY(1,1),Name1 varchar(100),Name2 varchar(100),Name3 varchar(100)) 
insert into @tbl 
select 'AA' ,'AB','AC'
UNION ALL
SELECT 'BA','BB','AA'
UNION ALL
SELECT 'CA','CB','CC'
UNION ALL
SELECT 'DA','DB','DD'
UNION ALL
SELECT 'EA','AB','EC'
UNION ALL
SELECT 'CC','FB','FC' 
SELECT * FROM @tbl a join @tbl b on a.name1<>b.name2 and a.name1<>b.name3 and a.Name2<>b.name3

1 个答案:

答案 0 :(得分:0)

下面的代码返回您想要的结果。如果它不能将行的Name1,Name2或Name3连接到任何其他行中的Name1,Name2或Name3值,则这些值必须是唯一的。

declare @tbl table (
    ID INT IDENTITY(1,1),
    Name1 varchar(100),
    Name2 varchar(100),
    Name3 varchar(100)
);

insert into @tbl values
    ('AA', 'AB', 'AC'),
    ('BA', 'BB', 'AA'),
    ('CA', 'CB', 'CC'),
    ('DA', 'DB', 'DD'),
    ('EA', 'AB', 'EC'),
    ('CC', 'FB', 'FC');

select T1.*
from @tbl T1
left join @tbl T2 on T2.ID != T1.ID and (
    (T1.Name1 in (T2.Name1, T2.Name2, T2.Name3))
    or (T1.Name2 in (T2.Name1, T2.Name2, T2.Name3))
    or (T1.Name3 in (T2.Name1, T2.Name2, T2.Name3))
    )
where T2.ID is null;

===编辑===

要忽略表中任何地方的重复值,即使它们位于同一行,也请尝试使用此版本...

declare @tbl table (
    ID INT IDENTITY(1,1),
    Name1 varchar(100),
    Name2 varchar(100),
    Name3 varchar(100)
);

insert into @tbl values
    ('AA', 'AB', 'AC'),
    ('BA', 'BB', 'AA'),
    ('CA', 'CB', 'CC'),
    ('DA', 'DB', 'DD'),
    ('EA', 'AB', 'EC'),
    ('CC', 'FB', 'FC');

;with UniqueValues as (
    select Value
    from (
        select Value=Name1 from @tbl
        union all
        select Value=Name2 from @tbl
        union all
        select Value=Name3 from @tbl
    ) D
    group by Value
    having count(1)=1
)
select T1.*
from @Tbl T1
join UniqueValues U1 on U1.Value=T1.Name1
join UniqueValues U2 on U2.Value=T1.Name2
join UniqueValues U3 on U3.Value=T1.Name3;