• Hello upstart,

    your use of datepart here is chaotic for me and I think there is a easier way to do it. You are interested only in compare the year/month, not the day, so using DATEDIFF(MONTH, startDate, endDate) should cover your needs.

    I think you can code your query like that,

    SELECT lr.*

    FROM lab_results lr, patient pat

    WHERE lr.patient_id = pat.patient_id

    and lr.sample_date >= CASE datediff(month, pat.start, getdate())

    WHEN 0 THEN '2199-01-01'

    WHEN 1 THEN dateadd(month, datediff(month, 0, GETDATE()) - 5, 0)

    ELSE DATEADD(month, DATEDIFF(month, 0, pat.start), 0)

    END

    Francesc