我从数据库中提取一个列,它看起来像这样:
Group
A
A
A
B
B
B
C
D
D
D
E
F
F
F
我需要删除唯一条目,因此应保留条目A,B,D和F,并删除条目C和E.
我根据这样的查询得到这一行:
select Group from table where type = 'rec';
基本上每种类型都应该有多个组,如果不是,则需要将其删除。
注意:我需要它自动化,而不仅仅是"删除C"和"删除E"因为有数千行,我不知道除非我找到它们,否则我需要删除哪些行。需要删除的行数也会发生变化,因此我需要根据计数自动执行此操作。
答案 0 :(得分:2)
一种方法是:
delete t
where "group" in (select "group" from t group by "group" having count(*) = 1);
根据您的示例代码:
delete t
where type = 'rec' and
"group" in (select "group" from t where type = 'rec' group by "group" having count(*) = 1);
你也可以这样做:
delete t
where type = 'rec' and
not exists (select 1
from t t2
where t2.group = t.group and t2.type = 'rec' and t2.rowid <> t.rowid
);
答案 1 :(得分:0)
根据您的评论判断,您所需要的只是总计。如果输入一次,则选择/删除它。如果你问我,分析函数是最好和最简单的方法:
SELECT * FROM
(
SELECT COUNT(grp) OVER (PARTITION BY grp ORDER BY grp) cnt -- number of occurances --
, grp
FROM
( -- convert to multi-row - REPLACE AAABBB with your actual column --
SELECT trim(regexp_substr('A A A B B B C D D D E F F F', '[^ ]+', 1, LEVEL)) grp
FROM dual -- from your table_name --
CONNECT BY LEVEL <= regexp_count('A A A B B B C D D D E F F F', '[^ ]+')
)
)
WHERE cnt = 1 -- Select/Delete only those that appeared once --
/
输出:
cnt|grp
--------
1 C
1 E
完整输出,如果你评论在哪里:
cnt|grp
--------
3 A
3 A
3 A
3 B
3 B
3 B
1 C
3 D
3 D
3 D
1 E
3 F
3 F
3 F
根据您的问题进行最终编辑。这会模拟你的表格:
WITH your_table AS
(
SELECT 'rec' grp_type FROM dual
UNION ALL
SELECT 'not_rec' grp_type FROM dual
)
SELECT grp_type FROM your_table WHERE grp_type = 'rec' -- apply all that above to this select --
/