I have some timestamps in a table and I want to create a dummy variable (0 or 1) that tests if the row above is equal to the current row, after the timestamps are sorted. I need to do this in different partitions. Is there a window function that can do this in SQL Server?
So I know my partition by column and order by column. From my knowledge of window functions I need to perhaps use a rank function, but is there a way to write this with nested functions using IIF
and LEAD
or LAG
to check for some condition between the rows in a partition?
Advertisement
Answer
SQL table represent unordered sets. If you have an ordering column separate from the timestamps you can use:
select t.*, (case when lag(timestamp) over (partition by <partition col> order by <order col>) = timestamp then 1 else 0 end) as flag from t;