Home > Back-end >  SQL command to remove groups of entries where all are equal (not merely DISTINCT)
SQL command to remove groups of entries where all are equal (not merely DISTINCT)

Time:07-19

i am so green in SQL that I don't even know how to properly phrase my question or look for an existing answer in stack overflow or anywhere else. Sorry!

Assume i have 3 columns. One is an ID and two data columns A and B. A single ID can have multiple entries. I like to remove all entries, where A and B are same for a given ID. Probably i give an example

ID A B
01 x y
01 x y
01 x y
02 x y
02 x z
02 x y

In this table I would like to remove all 3 entries that belong to ID 01 as A as well as B are all x and y, respectively. For ID 02, however, column B differs for the first and second entry. Therefore I like to keep ID 02. I hope this illustrates the idea sufficiently :-).

I am look for a 'scalable' solution, as I am not only looking at two data columns A and B, but actually 4 different columns.

Does anyone know how to set a proper filter in SQL to remove those entries according to my needs?

Many thanks.

Benjamin

CodePudding user response:

As for this, it basically doesn't matter how many coumns you actually have, as long as they are identical

this can be used for an as joining basis for a DELETE

WITH CTE AS
(SELECT DISTINCT "ID", "A", "B" FROM tab1),
CTE2 AS (SELECT "ID", COUNT(*) count_ FROM CTE GROUP BY "ID" HAVING COUNT(*)  >1) 
SELECT "ID" FROM CTE2
| ID |
| -: |
|  2 |

db<>fiddle here

  • Related