SQL: Returns the value of the column based on previous row values

advertisements

I have a table something like this

NAME    TIME                    IsTrue
A       15-05-2015 02:00        0
B       15-05-2015 03:00        1
C       15-05-2015 06:00        0
D       15-05-2015 13:00        0
E       15-05-2015 23:00        0
F       16-05-2015 04:00        0
E       16-05-2015 07:00        1
G       16-05-2015 23:00        0

I am trying to write a query whose output should be something like this

NAME    TIME                    IsTrue
A       15-05-2015 02:00        0
B       15-05-2015 03:00        1
C       15-05-2015 06:00        1
D       15-05-2015 13:00        1
E       15-05-2015 23:00        1
F       16-05-2015 04:00        0
E       16-05-2015 07:00        1
G       16-05-2015 23:00        1

Here you can observe that value of IsTrue is set on the condition that value of any row in last 24 hours is 1.

I don't want to make changes in the table itself but just return the value. Could anybody help?

Thanks in advance,

Regards, Ganesh.

P.S. I'm using Microsoft SQL Server if that matters.


This is simplest, but performance-wise sub-optimal solution. It uses correlated sub-query to calculate on each row:

SELECT
    [NAME]
  , [TIME]
  , (SELECT MAX(IsTrue+0) FROM TABLE1 it WHERE DATEADD(DD,1,it.TIME) > ot.TIME AND it.TIME <= ot.Time) [ISTRUE]
FROM Table1 ot

I don't how much data you have. It will work well enough with this sample, but if you have millions of rows, we might need to look for something better.

SQLFiddle DEMO

Note the +0 in MAX(IsTrue) to enable use aggregate functions on bit column