Skip to content
Advertisement

SQL GROUP BY and kind of rereduce afterwards

I’m using PostgreSQL v.11. I have a table with 3 columns. My goal is to find redundancy inside data.

First of all, I do a simple GROUP BY:

The result looks like this:

Now I would like to identify rows that have the same “block”, but different “date”. In this example, this is the case for row 2 and 3 (block = P10002)

For now, I use javascript to parse the complete resultset and find these 2 redundant rows (I use result.reduce(...))

But is there a way, in pure SQL, to extract this “rereduced” result?

The expected result is this:

It should be great to keep the two dates in the resultset, because I need to change the “block” for only one of them. If I don’t have the date column in the resultset, I will need to do a second request to find all the affected rows.

Here is a script for the table and data

Many thanks

Advertisement

Answer

You can do it with EXISTS:

If there is no case of duplicate dates for each client, block you could also use COUNT(*) window function:

See the demo.
Results:

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement