根据日期SQL减去值

时间:2013-08-15 20:24:20

标签: sql sql-server sql-server-2008

我的数据看起来像这样,但有更多的索引名称和索引值

dt                     indx_nm      indx_val
2013-08-13 00:00:00.000 ABQI        1571.93
2013-08-12 00:00:00.000 ABQI        1568.55
2013-08-09 00:00:00.000 ABQI        1566.1
2013-08-08 00:00:00.000 ABQI        1573.98
2013-08-07 00:00:00.000 ABQI        1567.42
2013-08-06 00:00:00.000 ABQI        1579.49
2013-08-13 00:00:00.000 ACNACTR     280.3931
2013-08-12 00:00:00.000 ACNACTR     275.1943
2013-08-09 00:00:00.000 ACNACTR     268.8868
2013-08-08 00:00:00.000 ACNACTR     265.7915
2013-08-07 00:00:00.000 ACNACTR     264.8321
2013-08-13 00:00:00.000 ACNITTR     145.3845
2013-08-12 00:00:00.000 ACNITTR     144.1252
2013-08-09 00:00:00.000 ACNITTR     143.2331
2013-08-08 00:00:00.000 ACNITTR     141.4968
2013-08-07 00:00:00.000 ACNITTR     140.6079

如何编写SQL查询以便按所有日期的上一个日期的indx_val减去indx_val。我想基本上找到每日回报。例如,对于ABQI1571.93 - 1568.55作为日期2012-08-13的返回,依此类推。我希望结果中包含dt列,indx_nm列和dly_rtn列。谢谢!

2 个答案:

答案 0 :(得分:4)

请尝试以下操作:

;with cte as (
    select dt, indx_nm, indx_val,
        rn = row_number() over (partition by indx_nm order by dt desc)
    from TableName
)
select c1.dt, c1.indx_nm, c1.indx_val - c2.indx_val as dly_rtn
from cte c1
    left join cte c2 on c2.rn = c1.rn + 1 and c2.indx_nm = c1.indx_nm
order by c1.indx_nm, c1.dt desc

另外,如果查询应该经常运行,我建议使用索引:

create unique index IX_TableName_1
    on TableName (indx_nm, dt desc) include (indx_val)

答案 1 :(得分:0)

select a.dt,a.indx_nm ,(b.indx_val-a.indx_val)dly_rtn From table1 a join 
Table1 b on a.dt=dateadd(dd,1,b.dt) and 
a.indx_nm=b.indx_nm