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

断了今生、忘了曾经 提交于 2021-02-10 06:32:54

问题


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

回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/9819898/referencing-a-previous-row-value-for-an-arithmetic-calculation-in-sql-server-200

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!