代码之家  ›  专栏  ›  技术社区  ›  Anonymous

SSMS-删除重复的分组值

  •  0
  • Anonymous  · 技术社区  · 7 年前

    Group|item
    1|desk
    1|phone
    1|book
    2|desk
    2|phone
    3|desk
    3|phone
    3|book
    4|Desk
    4|phone
    4|laptop
    

    如果组中的所有项都存在于另一个组中,则我要删除该组。如果有两个或更多的组都具有完全相同的项,那么我只想保留该组的一个实例,并除去其他实例。

    在上面的示例表中,我只保留组1和4,因为组2中的所有项都已存在于组1中,组3只是组3的副本。

    有没有一个简单的方法来实现这一点?我目前有一个解决方案,我选择上面的表到一个临时表,加入到自己的表组=组,在右边的表中获得不同的项目计数,计算项目匹配的实例数,如果这两个数字相同,我将删除该组(因为这将显示该组中的所有项目都存在于左侧的组中)

    这个解决方案的问题是,通过将表内部连接到组号不匹配的表本身,我必须创建一个(x^2)-x行数的表,而我处理的实际表有30000多行,我不希望创建一个包含大约90亿行的表。

    还请注意,我有数千种不同的项目。

    3 回复  |  直到 7 年前
        1
  •  1
  •   Yogesh Sharma    7 年前

    我会用 NOT EXISTS :

    select distinct t.group
    from table t
    where not exists (select 1 from table t1 where t1.group < t.group and t1.item = t.item);
    

    group

        2
  •  1
  •   Zaynul Abadin Tuhin    7 年前

      with cte as
        (
        select * from (
        select 1 as grp,'desk' as item union all
        select 1,'phone' union all
        select 1,'|book' union all
        select 2,'desk' union all
        select 2,'phone' union all
        select 3,'desk' union all
        select 3,'phone' union all
        select 3,'|book' union all
        select 4,'Desk' union all
        select 4,'phone' union all
        select 4,'laptop'
        ) t
        ) 
        select distinct t1.grp
        from cte t1
        where not exists (select 1 from cte t2 where t2.grp < t1.grp and t2.item = t1.item);
    
        3
  •  1
  •   Gordon Linoff    7 年前

    这相当复杂。您可以通过执行以下操作获得等效的组:

    select grp, min(contained_in_group)
    from (select t1.grp, t2.grp as contained_in_group
          from tt t1  join
               t t2
               on t1.item = t2.item 
          group by t1.grp, t2.grp, t1.num_grp
          having count(*) = count(t2.item) and count(*) = t1.num_grp
          ) x
    group by grp;
    

    rextester

    您想要的实际结果是:

    select distinct min(contained_in_group)
    from (select t1.grp, t2.grp as contained_in_group
          from tt t1  join
               t t2
               on t1.item = t2.item 
          group by t1.grp, t2.grp, t1.num_grp
          having count(*) = count(t2.item) and count(*) = t1.num_grp
          ) x
    group by grp;