1

我将数据存储在下表中 -

 [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,那么 row2 和 row3 的差异应该是 40,依此类推......示例数据如下......

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
4

1 回答 1

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
于 2013-02-23T12:12:07.510 回答