0

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

当前结果集

当前结果集

进一步让这些列阅读 1、2 和 3,我想在阅读和阅读之前的阅读之间有所区别。我希望我的结果集看起来像这样

期望的结果集

结果集

在这个结果集中计算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
4

2 回答 2

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
于 2013-10-22T18:42:56.390 回答
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
于 2013-10-22T18:32:32.643 回答