你能说明如何在t-sql中完成这项工作吗?
样本记录
accountnumber trandate
-------------------------
1000 02-11-2010
1000 02-12-2010
1000 02-13-2010
2000 02-10-2010
2000 02-15-2010
如何计算每个帐号的每笔交易之间的天数? 像这样
accountnumber trandate # of days
----------------------------------------
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
非常感谢!
答案 0 :(得分:3)
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
答案 1 :(得分:0)
您可以使用between and
select * from table1 where trandate between 'date1' and 'date2'
答案 2 :(得分:0)
希望这有帮助。
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
您还可以使用CTE表达式来提高性能。