t-sql - compute the difference between dates for each row
Can you show how can this be done in t-sql?
sample records
accountnumber trandate
-------------------------
1000          02-11-2010
1000          02-12-2010
1000          02-13-2010
2000          02-10-2010
2000          02-15-2010
How to compute the # of days between each transactions for each accountnumber? like this
accountnumber trandate       # of d开发者_如何转开发ays
----------------------------------------
1000          02-11-2010       0
1000          02-12-2010       1
1000          02-13-2010       1
2000          02-10-2010       0
2000          02-15-2010       5
Thanks a lot!
SELECT accountnumber, 
       trandate, 
       Datediff(DAY, a.trandate, (SELECT TOP 1 trandate 
                                  FROM   mytable b 
                                  WHERE  b.trandate > a.trandate 
                                  ORDER  BY trandate)) 
FROM   mytable a 
ORDER  BY trandate 
you can use between and 
select * from table1 where trandate  between 'date1' and 'date2'
Hope this helps.
Select A.AccountNo, A.TranDate, B.TranDate as PreviousTranDate, A.TranDate - B.Trandate as NoOfDays
from
(Select AccountNo, TranDate, Row_Number() as RNO over (Partition by AccountNo order by TranDate)) as A, 
(Select AccountNo, TranDate, Row_Number() as RNO over (Partition by AccountNo order by TranDate)) as B
Where A.AccountNo = B.AccountNo and A.RNO -1  = B.RNO
You can also use a CTE expression to increase preformance.
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论