每天的数据差异

时间:2012-03-21 20:23:14

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

我有一个名为Addim的表,数据如下:

TName           Idate        Number
Integrated      3/21/2012    26984013
Integrated      3/20/2012    26959226
Integrated      3/19/2012    26933190

我希望输出为:

Idate        Diff
3/21/2012    24787
3/20/2012    26036

我做了类似的事情:

Select Count(*),Idate
from dbo.Addim
group by Idate

但我得到这样的输出:

Idate        Diff
03/21/2012   1
03/20/2012   1

它的作用基本上与前一天有所不同 例如:  3/21/2012 the diff is 26984013(3/21/2012)-26959226(3/20/2012) = 24787 并为 3/20/2012是26959226(3/20/2012)-26933190(3/19/2012)= 26036

2 个答案:

答案 0 :(得分:3)

诀窍是将表格连接到前一天,就像这样:

DECLARE @Addim table (TName varchar(10), Idate datetime,Number int)
INSERT INTO @Addim VALUES ('Integrated','3/21/2012',26984013)
INSERT INTO @Addim VALUES ('Integrated','3/20/2012',26959226)
INSERT INTO @Addim VALUES ('Integrated','3/19/2012',26933190)


SELECT
    a.TName,a.Idate, a.Number-b.Number
    FROM @Addim             a
        INNER JOIN @Addim   b ON a.TName=b.TName AND a.Idate=b.Idate+1

输出:

TName      Idate                   
---------- ----------------------- -----------
Integrated 2012-03-21 00:00:00.000 24787
Integrated 2012-03-20 00:00:00.000 26036

(2 row(s) affected)

我不确定TName的重要性,所以我也加入了这个专栏,假设你在那里也有多个不同的值。如果没有像这样使用它,你可以很容易地从连接中删除它。

答案 1 :(得分:3)

试试这个:

;WITH CTE AS
(
    SELECT TName, Idate, Number, ROW_NUMBER() OVER(ORDER BY Idate) Corr
    FROM #Temp1--YourTable
)
SELECT A.Idate, A.number - B.number Diff
FROM CTE A
INNER JOIN CTE B
ON A.Corr = B.Corr + 1

这假定每天有一条记录,但即使缺少天数也会有效。