user1129988
user1129988

Reputation: 1576

Referencing a previous row value for an arithmetic calculation in SQL Server 2008 R2

I am working with SQL Server 2008 R2 and new to relational database. I need to run a simple calculation but the calculation involves using a previous row value.

Example:

(Value of X) / ((Value of Y at time t + Value of Y at time t-1) / 2)

Example:

select (x/[(y@time,t + y@time,t-1)/2]) as 'Value'
from datatable
select ((c.ACHQ)/(c.RECTQ(row:n) + c.RETQ(row:n-1))/2) as 'AR'
from co_ifndq c
where c.GVKEY in 
(select GVKEY 
    from spidx_cst
    where DATADATE = '2012-03-12'
    and INDEXID = '500')
and c.DATAFMT = 'std'
and c.DATADATE > '1990-12-30'
order by c.GVKEY, datadate desc

Upvotes: 2

Views: 3604

Answers (2)

Cenas
Cenas

Reputation: 116

As I understand you want to make a calculation base on a date difference and not really on a row order, right?

If so, if you have a table like this

CREATE TABLE YourTable(
    ACHQ float ,
    RECTQ float,
    DATE datetime)

INSERT INTO YourTable VALUES    (100,10,'20100101')
INSERT INTO YourTable VALUES    (200,20,'20110101')
INSERT INTO YourTable VALUES    (300,30,'20120101')
INSERT INTO YourTable VALUES    (400,40,'20130101')
INSERT INTO YourTable VALUES    (500,50,'20140101')
INSERT INTO YourTable VALUES    (600,60,'20150101')

you can do something like this

SELECT
    ((c.ACHQ)/(c.RECTQ + cPreviousYear.RECTQ)/2) as 'AR'
FROM
    YourTable c
        LEFT JOIN YourTable cPreviousYear
            ON YEAR(c.Date) - 1 = YEAR(cPreviousYear.Date)

I simplified the calculation just to show that you can link the table to itself directly to the row with the wanted date difference and then calculate the value. you can even use ON DATEADD(y, -1, c.Date) = cPrevious.Date if you want the real date diference

Sorry if I missed the point.

Upvotes: 2

user359040
user359040

Reputation:

Assuming x, y and t are all on the same table, try:

;with cte as (
select m.*, row_number() over (order by t) rn from mytable)
select t1.t, t1.x / ((t1.y + t0.y)/2) as [value]
from cte t1
left join cte t0 on t0.rn = t1.rn-1

EDIT: based on the query supplied:

;with cte as (
select c.*, row_number() over (partition by c.GVKEY order by c.DATADATE) rn 
from co_ifndq c
where c.GVKEY in 
(select GVKEY 
 from spidx_cst
 where DATADATE = '2012-03-12' and INDEXID = '500')
and c.DATAFMT = 'std'
and c.DATADATE > '1990-12-30'
)
select t1.GVKEY, t1.DATADATE, t1.ACHQ / ((t1.RETQ + t0.RETQ)/2) as [value]
from cte t1
left join cte t0 on t1.GVKEY = t0.GVKEY and t0.rn = t1.rn-1
order by t1.GVKEY, t1.datadate desc

Upvotes: 1

Related Questions