if want querying the following table :
EventDateTime (DateTime), Host (guid), Flag ( bit)
2013-04-01 05:00, {id-x}, 0
2013-04-01 05:01, {id-x}, 0
2013-04-01 05:02, {id-x}, 0
2013-04-01 05:03, {id-x}, 0
2013-04-01 05:04, {id-x}, 1
2013-04-01 05:05, {id-x}, 1
2013-04-01 05:06, {id-x}, 1
2013-04-01 05:07, {id-x}, 0
2013-04-01 05:08, {id-x}, 0
2013-04-01 05:09, {id-x}, 0
2013-04-01 05:10, {id-x}, 0
2013-04-01 05:11, {id-x}, 1
2013-04-01 05:12, {id-x}, 1
2013-04-01 05:13, {id-x}, 1
2013-04-01 05:14, {id-x}, 1
2013-04-01 05:15, {id-x}, 0
and the result should be:
2013-04-01 05:04, {id-x}, 1
2013-04-01 05:07, {id-x}, 0
2013-04-01 05:11, {id-x}, 1
2013-04-01 05:15, {id-x}, 0
i have try it with LAG,LEAD and OVER Clause. but no luck 🙁
Best Answer
Here is a version for SQL Server 2012 using the new
LAG
feature:Here is a version for SQL Server 2008 using a self join: