2013-02-23 88 views
1

我下表中存儲的數據之間的差 -TSQL - 獲取每一行值

[dbo].[readings] 

    [id] [int] IDENTITY(1,1) NOT NULL, 
    [device_id] [int] NOT NULL, 
    [time] [datetime] NOT NULL,  
    [reading] [decimal](18, 2) NOT NULL, 
    [shift_id] [int] NULL, 

的值被存儲在讀出列。我想要的是每行之間的讀數差異。即,如果已經ROW1讀取= 1520和ROW2已讀取= 1560然後差應在40等爲ROW2和ROW3 ..... 樣本數據是如下....

67118 5 2013-02-23 04:21:45.107 1.00 42 
67119 5 2013-02-23 04:21:45.247 4.00 42 
67120 5 2013-02-23 04:21:45.340 7.00 42 
67121 5 2013-02-23 04:21:45.433 9.00 42 
67122 5 2013-02-23 04:21:45.527 11.00 42 
67123 5 2013-02-23 04:21:45.620 13.00 42 
67124 5 2013-02-23 04:21:45.713 16.00 42 
67125 5 2013-02-23 04:21:45.807 18.00 42 
67126 5 2013-02-23 04:21:45.900 20.00 42 
67127 5 2013-02-23 04:21:45.993 22.00 42 
67128 5 2013-02-23 04:21:46.087 24.00 42 
67129 5 2013-02-23 04:21:46.183 26.00 42 
67130 5 2013-02-23 04:21:46.277 28.00 42 
67131 5 2013-02-23 04:21:46.370 30.00 42 
67132 5 2013-02-23 04:21:46.463 31.00 42 
67133 5 2013-02-23 04:21:46.557 33.00 42 
67134 5 2013-02-23 04:21:46.650 35.00 42 
67135 5 2013-02-23 04:21:46.743 37.00 42 
67136 5 2013-02-23 04:21:46.837 39.00 42 
67137 5 2013-02-23 04:21:46.930 41.00 42 
67138 5 2013-02-23 04:21:47.023 43.00 42 
67139 5 2013-02-23 04:21:47.117 45.00 42 
67140 5 2013-02-23 04:21:47.210 47.00 42 
67141 5 2013-02-23 04:21:47.303 49.00 42 
67142 5 2013-02-23 04:21:47.400 50.00 42 
67143 5 2013-02-23 04:21:47.493 52.00 42 
67144 5 2013-02-23 04:21:47.600 55.00 42 
67145 5 2013-02-23 04:21:47.693 56.00 42 
67146 5 2013-02-23 04:21:47.790 58.00 42 
67147 5 2013-02-23 04:21:47.883 60.00 42 

進一步更我需要每小時每班每小時的數據,如下圖所示。我已經寫存儲過程和產生的樣本數據..

2013-02-23 1st 4 5 391.00 1.00 390.00 
2013-02-23 1st 7 5 2762.00 1019.00 1743.00 
2013-02-23 2nd 8 5 3270.00 2764.00 506.00 
2013-02-23 3rd 16 5 6255.00 4102.00 2153.00 
+1

你已經試過什麼疑問? – Matt 2013-02-23 12:05:35

+2

和SQL Server的版本? – 2013-02-23 12:28:15

+1

對於第二部分,您至少需要提供該數據集的列標題以及「每小時移位」的解釋。 – muhmud 2013-02-23 12:42:16

回答

0

關於SQLServer中的第一個問題2005+你可以試試這個

;WITH cte AS 
( 
    SELECT *, ROW_NUMBER() OVER(PARTITION BY device_id ORDER BY [time]) AS NId 
    FROM [dbo].[readings] 
) 
    SELECT c1.[id], c1.[device_id], c1.[time], 
     c1.reading AS currRow, ISNULL(c2.reading, 0) AS nextRow, 
     c1.reading - ISNULL(c2.reading, c1.reading) AS diff 
    FROM cte c1 LEFT JOIN cte c2 ON c1.device_id = c2.device_id 
            AND c1.NId + 1 = c2.NId 
+0

嘿亞歷山大,我認爲你是99.99%關閉。明天早上我會試一試。謝謝您的幫助。 – 2013-02-23 13:33:24

+0

Woha ....你的答案奏效。感謝您的幫助 – 2013-02-24 06:22:20

+0

嘿亞歷山大,我進入新的問題,我已經要求在這個職位的解決方案http://stackoverflow.com/questions/15064775/the-difference-between-each-row-value-sum-error – 2013-02-25 12:49:42