日期:2014-05-16 浏览次数:20651 次
----------------------------------------------------------------
-- Author :fredrickhu(小F,向高手学习)
-- Date :2014-03-31 10:38:20
-- Verstion:
-- Microsoft SQL Server 2008 (RTM) - 10.0.1600.22 (Intel X86)
-- Jul 9 2008 14:43:34
-- Copyright (c) 1988-2008 Microsoft Corporation
-- Enterprise Edition on Windows NT 6.1 <X86> (Build 7601: Service Pack 1)
--
----------------------------------------------------------------
--> 测试数据:[test]
if object_id('[test]') is not null drop table [test]
go
create table [test]([FTime] datetime,[Funds] int)
insert [test]
select '2014/1/1',100 union all
select '2014/1/5',105 union all
select '2014/1/8',102 union all
select '2014/1/9',99 union all
select '2014/1/10',103
--------------开始查询--------------------------
;WITH f AS
(
SELECT ROW_NUMBER()OVER(ORDER BY FTime) AS id, * FROM dbo.test
)
SELECT *,ISNULL((SELECT t.Funds-Funds FROM f WHERE id=t.id-1 AND FTime<t.FTime),Funds) AS Funds FROM f t
----------------结果----------------------------
/* id FTime Funds
-------------------- ----------------------- ----------- -----------
1 2014-01-01 00:00:00.000 100 100
2 2014-01-05 00:00:00.000 105 5
3 2014-01-08 00:00:00.000 102 -3
4