SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

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

Rasta Pickles
Posting Yak Master

United Kingdom
169 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

USA
1585 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)
values
    (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
)
select
    a.code, a.month, a.value - b.value value
from
    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

visakh16
Very Important crosS Applying yaK Herder

India
52249 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
CROSS APPLY (SELECT TOP 1 value
             FROM table
             WHERE month < t.month 
             ORDER BY month DESC)t1


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

Rasta Pickles
Posting Yak Master

United Kingdom
169 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  
 New 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.06 seconds. Powered By: Snitz Forums 2000