Assuming you have sql 2005, here is a way compare a "current" row with a "previous" row:------------------------------------------------------------------set up a table variable similar to your actual tabledeclare @t table (date datetime ,[open] money ,high money ,low money ,[close] money)insert @tselect '2008-01-22', 1344.22, 1354.3, 1327.04, 1353.11 union allselect '2008-01-21', 1362.21, 1367.94, 1339.34, 1342.53 union allselect '2008-01-20', 1348.39, 1363.71, 1336.55, 1360.03 ------------------------------------------------------------------see the raw table dataselect * from @t--Create a CTE (common table expression) with a sequencial column [rn];with cte as(select date ,[open] ,high ,low ,[close] ,row_number() over (order by [date] desc) rnfrom @t)--select from our CTE using a SELF JOIN so that we can associate a CURRENT row with a PREVIOUS row.select curr.[date] as [CurrDate] ,prev.[date] as [PrevDate] --,curr.[open] as [currOpen --,prev.[open] as [prevOpen ,CurrOpenGreaterThanPrevClose = case when curr.[Open] > prev.[close] then 1 else 0 end ,CurrLowLessThanPrevClose = case when curr.[low] <= prev.[close] then 1 else 0 end ,CurrHighLessThanPrevClose = case when curr.[high] >= prev.[close] then 1 else 0 endfrom cte currjoin cte prev on prev.rn-1 = curr.rnoutput:date open high low close----------------------- --------------------- --------------------- --------------------- ---------------------2008-01-22 00:00:00.000 1344.22 1354.30 1327.04 1353.112008-01-21 00:00:00.000 1362.21 1367.94 1339.34 1342.532008-01-20 00:00:00.000 1348.39 1363.71 1336.55 1360.03date CurrOpenGreaterThanPrevClose CurrLowLessThanPrevClose CurrHighLessThanPrevClose----------------------- ---------------------------- ------------------------ -------------------------2008-01-22 00:00:00.000 1 1 12008-01-21 00:00:00.000 1 1 1
Be One with the OptimizerTG