sql - 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”的值是什么,所以我无法使用特定值进行查询。
解决方案
您可以将父组和子组对获取为:
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
推荐阅读
- javascript - ajax jquery 错误显示 [object Object]
- python - psycopg2 标识符中的模式名称
- typo3-7.6.x - “新闻迁移”设置
- sql - 如何使用表中的 3 个连接更新数据?
- ios - 圆形菜单 - 仅在单击区域而不只是图标时创建菜单和调用操作
- json - 如何在 Wikidata 中对数据进行 JSON 或 RDF 批量导入?
- database - OAuth2.0的数据库方案
- python - netcdf python的无效语法ncdump
- android - Glide 不从文件加载图像
- mysql - 使用 pyspark 更新 MySQL 表