SQL DELETE group of records based on opposite group being empty

sny

In table T, I'm trying to delete all records in a groups having same value of A, but only if all members of this group have B set to 'x'.

Given the Table T:

+-------+--------+
|   A   |   B    |
+-------+--------+
|    2  |   ''   |
|    2  |   'x'  |
|    2  |   ''   |
|    8  |   'x'  |
|    8  |   'x'  |
|   15  |   ''   |
|   15  |   ''   |
+-------+--------+

The two records with A == 8 have to be deleted as all two of them have B==1. The group of A==2 has mixed value of B so it stays. And group of A==15 doesn't have all of it's B equal to 1 it also stays.

Is this possible to do by one query?

If not, any other way that is fast enough for a table with a lot of records?

Iłya Bursov

you can try this query:

delete from T
where A in (
select A
from T
group by A
having sum(B) = count(*)
)

if column b can contain non 0/1 values, you can add additional conditions:

having sum(B) = count(*) and min(b)=1 and max(b)=1

if you can't use numeric values, you can just use min/max, like

having min(b)='x' and max(b)='x'

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

sql delete based on group by

From Dev

Delete duplicates based on Group By - SQL

From Dev

Group Sequential SQL Records

From Dev

SQL Query to group records

From Dev

Group Sequential SQL Records

From Dev

How delete records that are not the maximum of a group from an SQL table

From Dev

How delete records that are not the maximum of a group from an SQL table

From Dev

How to concatenate records based on a GROUP BY?

From Dev

Group more records based on values

From Dev

SQL group by - which records are grouped

From Dev

Oracle SQL - Group and Detail records

From Dev

SQL group by - which records are grouped

From Dev

Group records with multiple sets in sql

From Dev

Delete pandas group based on condition

From Dev

Delete pandas group based on condition

From Dev

MongoDB Delete records where group by count

From Dev

Update specific records based on some group

From Dev

mysql group records based on a column value

From Dev

how to group records based on dates in mongodb

From Dev

Listing based on a particular SQL Group

From Dev

SQL - Group By based on optional flag

From Dev

Group by both similar and opposite elements

From Dev

Mysql group by does opposite of grouping by

From Dev

Group by both similar and opposite elements

From Dev

SQL Server: only group consecutive records when using GROUP BY

From Dev

SQL deleting records with group by multiple tables

From Dev

SQL SERVER - Group records by n minutes interval

From Dev

SQL GROUP BY and retrieve last child records

From Dev

Oracle SQL query to group consecutive records