首页 > 解决方案 > SQL从同一个表中删除子集

问题描述

我试过在类似的问题上查找这个,但它们似乎并不相同。

无论组中值的顺序如何,我都试图从表中删除较小的子集组。因此,保留较大的组并删除较小的组,只要它们是较大组的子集。

Group   Item
1       A
1       B
1       C
1       D
2        B
2        A
3       B
3       E
3       A
4        Z
4        W
4        Y

在此示例中,由于第 1 组最大,我想保留它。我还想保留第 4 组,因为它不是另一个组的子集。但我想删除第 2 组(因为它是第 1 组的子集)但不删除第 3 组(因为它不是完整的子集)。

我还要提一下,数据量很大,无法确定“item”或“group”的值是什么,所以我无法使用特定值进行查询。

标签: sqlsubset

解决方案


您可以将父组和子组对获取为:

select t1.group as parent_group, t2.group as childgroup
from t t2 left join
     t t1
     on t1.item = t2.item and t1.group <> t2.group
group by t1.group, t2.group
having count(t1.item) = (select count(*) from t tt1 where tt1.group = t1.group);

这将检查子 ( t2) 中的所有内容是否在父 ( t1) 中。

如果您知道没有组是相同的,那么您可以删除所有子组。如果它们可以相同,则将其更改having为:

having count(t1.item) = (select count(*) from t tt1 where tt1.group = t1.group) and
       count(*) <> count(t1.item)   -- not an exact match

推荐阅读