在SQL Server 2008 R2中引用算术计算的前一行值

时间:2012-03-22 09:56:57

标签: sql sql-server sql-server-2008 tsql

我正在使用SQL Server 2008 R2和新的关系数据库。我需要运行一个简单的计算,但计算涉及使用前一行值。

示例:

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

示例:

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

2 个答案:

答案 0 :(得分:1)

假设x,y和t都在同一个表上,请尝试:

;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

编辑:根据提供的查询:

;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

答案 1 :(得分:0)

据我所知,您希望根据日期差异进行计算,而不是按行顺序计算,对吧?

如果是这样,如果您有这样的表

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')

你可以做这样的事情

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)

我简化了计算,只是为了表明您可以将表直接链接到具有所需日期差异的行,然后计算该值。如果你想要真实的日期差异,你甚至可以使用ON DATEADD(y, -1, c.Date) = cPrevious.Date

很抱歉,如果我错过了这一点。