日期:2014-05-16  浏览次数:20596 次

SQL查询每两行数据差
网上搜了半天,没找到合适的,SQL不是很熟,但是觉得这个应该可以通过一条SQL语句实现的,求指点!
数据格式:
表 test
FTime          Funds
2014/1/1      100
2014/1/5      105
2014/1/8      102
2014/1/9       99
2014/1/10     103

希望得到结果:
FTime          Funds      sub
2014/1/1      100          100
2014/1/5      105           5
2014/1/8      102           -3
2014/1/9       99            -3
2014/1/10     103          4

------解决方案--------------------
----------------------------------------------------------------
-- 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