I want to make an condition on dates with window functions

I'm trying to calculate the difference between two events where the condition X is happening and I also have the condition that if the events happens in the same day, the second event will take the previous date not the one earlier on that same date. (Does it make sense ?)

I found a way to do it with a subquery but it's taking so much time, this is why I want to know if there is another way to do it.

(

SELECT MAX(ld2.date)

FROM table ld2

WHERE ld2.condition = 'X'

AND ld2.id = ld.id

AND ld2.date < ld.date

) AS last_date,

So I tried using a MAX function and I want to apply this condition to my window function :

MAX(CASE WHEN condition = 'X' AND date < LEAD(date) OVER (PARTITION BY id ORDER BY date) THEN date END) OVER (PARTITION BY id ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) AS last_date

I tried a lead function but i've got the error : may not be nested inside another window function.

I'm working with snowflake, does anyone have an idea of how I can do that?