Skip to content
Advertisement

SQL: Is there a way to capture “once every 45 days”?

First time post, but I’ve stumbled across Stackoverflow for years.

A patient might get a particular lab test many many times in a span of a few months. However, to reduce duplication, I only want to capture these results once every 45 days. So if a patient had a lab test today, I can ignore the next 45 days’ worth of lab tests. But if a patient gets a repeat lab test, say, on day 51, I want to reset the “clock” and ignore the next 45 days’ worth of lab tests.

Here’s generally what I’m trying to do:

(in my final product, I don’t necessarily need the DayNum, KeepThis, or DaysSinceLastKeptTest columns. I just need the 3 “Yes” rows.)

I’m trying to do this in SQL, but can’t figure it out. I’ve thought about temporary tables or subqueries, and I’m just learning about OVER/PARTITION BY as a possible way to tackle this.

I appreciate any help or ideas you may have. Thanks!

Advertisement

Answer

With a recursive CTE you can do it:

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