Please start any new threads on our new site at We've got lots of great SQL Server experts to answer whatever question you can come up with.

Our new SQL Server Forums are live! Come on over! We've restricted the ability to create new threads on these forums.

SQL Server Forums
Profile | Active Topics | Members | Search | Forum FAQ
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Calculating differences between months?
 Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Rasta Pickles
Posting Yak Master

United Kingdom
174 Posts

Posted - 03/12/2013 :  14:52:16  Show Profile  Reply with Quote
Any help greatly appreciated, I'm struggling with this one.

Assume my table has three fields: code, month, value. The month field is in the format yyyymm.

Here's what I'm trying to achieve; assume the following.

code month value

1234 201201 75
1234 201202 95
1234 201203 80

What I'm looking for as output is:

code month value
1234 201202 20
1234 201203 -15

The difference between 201202 and 201201 is 20 (95-75)
The difference between 201203 and 201202 is -15 (80-95)

This seems impossible to achieve, does anyone have any pointers?

Many thanks for taking the time to read.

Edited by - Rasta Pickles on 03/12/2013 15:00:44

Bustaz Kool
Flowing Fount of Yak Knowledge

1834 Posts

Posted - 03/12/2013 :  18:14:08  Show Profile  Reply with Quote
declare @MyTable table (    -- Stuff you should be supplying
    code  int not null,
    month char(6) not null,
    value int not null

insert into @MyTable (code, month, value)
    (1234, '201201', 75),
    (1234, '201202', 95),
    (1234, '201203', 80)

;with Ordered              -- Possible solution
as (
select code, month, value, row_number() over (partition by code order by month) rn
from @MyTable
    a.code, a.month, a.value - b.value value
    Ordered a
inner join
    Ordered b
        on  a.code = b.code
        and a.rn = b.rn + 1

There are two kinds of light -- the glow that illuminates, and the glare that obscures. -James Thurber
Go to Top of Page

Very Important crosS Applying yaK Herder

52326 Posts

Posted - 03/13/2013 :  00:38:16  Show Profile  Reply with Quote

SELECT t.code, t.month, t.value - t1.value AS value
FROM table t
             FROM table
             WHERE month < t.month 
             ORDER BY month DESC)t1

SQL Server MVP

Go to Top of Page

Rasta Pickles
Posting Yak Master

United Kingdom
174 Posts

Posted - 03/13/2013 :  14:47:12  Show Profile  Reply with Quote
Thanks both, will try when I'm next in work.
Go to Top of Page
  Previous Topic Topic Next Topic  
 Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.03 seconds. Powered By: Snitz Forums 2000