获得价值与先前价值之间的差异

时间:2013-10-22 18:28:22

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

我有一个查询从不同的表中提取数据,我的结果集如下

当前结果集

Current Result Set

除了阅读这些专栏1,2和3之外,我希望在阅读之前阅读和阅读之间有区别。我希望我的结果集看起来像这样

所需的结果集

Result SET

在此结果集中计算R1_Change1我正在区分

44 - 38 =  6
38 - 46 = -8
46 - 17 = 17
17 - 25 = -8 

等等....请提前告知。我已经添加了测试数据的代码,请看一下并提出建议。到目前为止我得到的答案并没有给出预期的结果,但也不是到目前为止。

CREATE TABLE TestTable
(
[Date] DateTime,
Reading1 int,
Reading2 int,
Reading3 int
)
GO

INSERT INTO TestTable
VALUES ('2013-10-01 00:00:00.000',44,27,22),
('2013-09-17 00:00:00.000',38,55,54),
('2013-09-11 00:00:00.000',46,63,65),
('2013-09-03 00:00:00.000',17,96,23),
('2013-08-21 00:00:00.000',25,87,54),
('2013-08-11 00:00:00.000',63,25,25)
GO

2 个答案:

答案 0 :(得分:3)

这应该做:

;WITH CTE AS
(
    SELECT  *,
            RN = ROW_NUMBER() OVER(ORDER BY [Date])
    FROM (/*Your query here*/) A
)
SELECT  X.[Date],
        X.Reading1,
        ISNULL(X.Reading1,0) - ISNULL(Y.Reading1,0) R1_Change1,
        X.Reading2,
        ISNULL(X.Reading2,0) - ISNULL(Y.Reading2,0) R2_Change2,
        X.Reading3,
        ISNULL(X.Reading3,0) - ISNULL(Y.Reading3,0) R3_Change3
FROM CTE X
LEFT JOIN CTE Y
    ON X.RN = Y.RN + 1

答案 1 :(得分:1)

尝试这样的事情 -

select
[Date],
[Reading1],
R1_Change = [Reading1] - (select top 1 [Reading1] from Readings b where b.[Date] < a.[Date] order by b.[Date] desc),
[Reading2],
R2_Change = [Reading2] - (select top 1 [Reading2] from Readings b where b.[Date] < a.[Date] order by b.[Date] desc),
[Reading3],
R3_Change = [Reading3] - (select top 1 [Reading3] from Readings b where b.[Date] < a.[Date] order by b.[Date] desc),
from
Readings a