Skip to content
Advertisement

PostgreSQL: Return gaps and value mismatches between columns

Imagine the following data:

enter image description here

I am interested in returning the entries where there is a gap in the data for a particular student, where the category changes from one year to another, or both. So the output that I’m after is:

enter image description here

The reason why id 4 would not be returned is because there is actually no gap or difference between the values. Imagine the student only joined in year_2 and their last year was year_4. I’m only interested in returning gaps and/or scores different than the max score.

The code I’m using is:

The issue with it is that it only returns me ids 2 and 3 – it is missing id 1 that has a gap (null value) in year_4.

How should I edit my code to return both gaps and values different from the max score?

Advertisement

Answer

Finding the gaps is the challenge here. To check for this, you can make a string from the values and a regular expression to find any digit-x-digit combinations, which you want to detect

dbfiddle.

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