当前位置: 代码迷 >> Sql Server >> sql server 如何循环求相邻值的差
  详细解决方案

sql server 如何循环求相邻值的差

热度:45   发布时间:2016-04-25 00:51:24.0
sql server 怎么循环求相邻值的差
    a         b                  c
    002       2002-01-30        1000
    002       2002-02-28       1500
    002      2003-04-30        2800
    002      2003-05-30        3000
    003     2003-04-30        2800
    003     2003-05-30        3000
要得到这样的结果集
a         b                  c          d
    002       2002-01-30     1000   1000
    002       2002-02-28      1500   500
    002      2003-04-30        2800  2800
    002      2003-05-30        3000  200
    003     2003-04-30        2800  2800
    003     2003-05-30        3000   200
不同年份相邻的月份才能相减我用的update语句不对 想用循环怎么写


 
------最佳解决方案--------------------
-- 测试数据:#
if object_id('tempdb.dbo.#') is not null drop table #
create table #(a varchar(8), b date, c int, d int)
insert into #(a,b,c)
select '002', '2002-01-30', 1000 union all
select '002', '2002-02-28', 1500 union all
select '002', '2003-04-30', 2800 union all
select '002', '2003-05-30', 3000 union all
select '003', '2003-04-30', 2800 union all
select '003', '2003-05-30', 3000

update a set a.d = a.c-isnull(b.c,0) from # a left join # b on a.a=b.a and year(a.b)=year(b.b) and month(a.b)=month(b.b)+1
select * from #
/*
a        b          c           d
-------- ---------- ----------- -----------
002      2002-01-30 1000        1000
002      2002-02-28 1500        500
002      2003-04-30 2800        2800
002      2003-05-30 3000        200
003      2003-04-30 2800        2800
  相关解决方案