2012-03-21 66 views
2

我有一個名爲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
2012/3/20是26959226(2012/3/20)-26933190(3/19/2012 )= 26036

回答

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 

OUTPUT:

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的重要性,所以我也加入了這個專欄,假設你也有多個不同的值。如果不是那樣使用,您可以輕鬆地將它從連接中移除。

+0

太棒了非常感謝你 – peter 2012-03-21 20:33:07

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 

這是假定每天一個記錄,但它會工作,即使有失蹤天。