我的主要问题在以下帖子中得到解决
我有一个问题是对每一行之间的读数值求和。
id device_id time reading shift_id
150323 3 2013-02-25 15:22:01.273 999948.00 43
150324 1 2013-02-25 15:22:01.423 999962.00 43
150325 3 2013-02-25 15:22:01.463 999966.00 43
150326 1 2013-02-25 15:22:01.610 999979.00 43
150327 3 2013-02-25 15:22:01.650 999983.00 43
150328 1 2013-02-25 15:22:01.810 999997.00 43
对于上述情况,我得到了结果,但是在以下情况下,根据提供给我的解决方案,读数正确,但我想增加差异......
id device_id time reading shift_id
150322 1 2013-02-25 15:22:01.233 999945.00 43
150323 3 2013-02-25 15:22:01.273 999948.00 43
150324 1 2013-02-25 15:22:01.423 999962.00 43
150325 3 2013-02-25 15:22:01.463 999966.00 43
150326 1 2013-02-25 15:22:01.610 999979.00 43
150327 3 2013-02-25 15:22:01.650 999983.00 43
150328 1 2013-02-25 15:22:01.810 999997.00 43
150329 3 2013-02-25 15:22:01.853 1.00 43
150330 1 2013-02-25 15:22:02.000 15.00 43
150331 3 2013-02-25 15:22:02.040 18.00 43
150332 1 2013-02-25 15:22:02.187 32.00 43
上述读数的结果如下
Day Shifts Hour Device ID Count1
2013-02-25 2nd 11 1 39145.00
2013-02-25 2nd 11 3 39148.00
2013-02-25 2nd 12 1 248022.00
2013-02-25 2nd 12 3 248022.00
2013-02-25 2nd 13 1 389195.00
2013-02-25 2nd 13 3 389197.00
2013-02-25 2nd 14 1 201855.00
2013-02-25 2nd 14 3 201854.00
2013-02-25 2nd 15 1 -877108.00
2013-02-25 2nd 15 3 -877112.00
这两个负值应该是正值,值应该是 122892 - 122889。
注意:读取的最大值将始终为 999999.00,之后我将再次从 0 开始到 999999.00,然后再次从 0 开始。这基本上是计数的计数设备。以下是堆栈溢出时建议的查询,我根据需要进行了一些修改
declare @fromdate datetime;
declare @todate datetime;
declare @total as decimal(18,2);
SET @fromdate = '2/23/2013 10:51:17 AM';
SET @todate ='2/25/2013 12:10:56 PM';
WITH cte AS
(
SELECT *,
ROW_NUMBER() OVER(PARTITION BY device_id ORDER BY [time]) AS NId
FROM [dbo].[readings] r
where cast(r.time as date)>= CAST(@fromdate as date) and
cast(r.time as date) <= CAST(@todate as date) and
r.device_id<>5
)
SELECT CAST (c1.[time] as DATE) as [Day],
(
select s.name from shifts s where s.id = c1.shift_id
) as Shifts,
DATEPART(hour,c1.time) as [Hour],
c1.device_id as [Device ID],
(select
case when sum(c2.reading - ISNULL(c1.reading, c2.reading)) < 0 then
sum(c1.reading - ISNULL(c2.reading, c1.reading))
else
sum(c2.reading - ISNULL(c1.reading, c2.reading))
end
) AS Count1
FROM cte c1 left JOIN cte c2 ON c1.device_id = c2.device_id AND
c1.NId + 1 = c2.NId
group by cast(c1.time as DATE), c1.shift_id , DATEPART(hour,c1.time), c1.device_id
order by cast(c1.time as DATE), c1.shift_id,DATEPART(hour,c1.time), c1.device_id