Skip to content
Advertisement

SQL Teradata – Comparing row values but skipping some rows

Lets say I have these date values in my table:

I need to keep only the dates that are 2 months appart from the previous “good” one.

So, I start with:

#1 is the first one, I keep it as a good one.

#2 is only one month appart, so not good.

#3 is two months appart from #1 (I ignore #2 because it was not good).

#4 is two months appart from #3, so I keep it

#5 is not good because it is only one month from #4

#6 is not good because it is only one and a half month from #4 (#5 is ignored because it was not good).

#7 is good because it is two months appart from #4 which was the last good one.

Is there an easy, clean way to do that?

I started with a dense_rank() over and compare them with the previous rank but I fail to figure out how to ignore the bad dates.

Advertisement

Answer

This is an iterative process. You can solve it using a recursive CTE. Given that you are dealing with dates and months, your data is not too large, so this might be a reasonable solution.

Date arithmetic varies significantly among databases. The following is the idea:

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