如果已交换仪表,则循环访问SQL记录以获得整个仪表读数

时间:2012-10-18 01:11:35

标签: sql

我有一张桌子,用于输入车辆的每周Hobbs小时表读数。我需要能够累计一段时间内每辆车使用的总小时数。我遇到的问题是,有时仪表一旦发生故障就会被换掉并换成新的仪表,这是不可编程的,我必须从零时开始,所以我需要循环读取每个仪表读数并确定仪表是否有已被交换并在我的代码中对其进行了说明。我对游标并不大,但可能必须使用一个来创建一个可以工作的存储过程,除非有人有更好的解决方案我应该尝试。我试图想办法CTE可能有所帮助,但还没有。

表结构是:

ReadingDate Datetime
EquipmentId Int
MeterReading  decimal(18,2)

I.m计划创建累积变量,循环遍历游标中的行并将读取差异添加到变量中。 因此,当我循环并看到仪表读数小于之前的读数时,我必须换掉仪表,并且必须考虑它。我想如果我要向前看下一个读数并且它低于当前值,我会跳过一次求和动作,然后开始将积分变量加到差值变量上。有更好的方法吗?感谢。

1 个答案:

答案 0 :(得分:2)

这适用于SqlServer:

SELECT t1b.EquipmentId, 
       t1a.ReadingDate As StartDate, 
       t1b.ReadingDate AS EndDate,
       CASE 
         WHEN t1b.Reading >= t1a.Reading THEN t1b.Reading - t1a.Reading 
         ELSE t1b.Reading
      END AS Hours
FROM MeterReadings AS t1a
JOIN (select t11.EquipmentId, 
             t11.ReadingDate AS Date1, 
             (SELECT MIN(t13.ReadingDate)  
                FROM MeterReadings AS t13 
               WHERE t13.EquipmentId = t11.EquipmentId 
                AND t13.ReadingDate > t11.ReadingDate 
           Group By t13.EquipmentId) AS NextReadingDate
       from MeterReadings AS t11) AS rd ON t1a.EquipmentId = rd.EquipmentId 
                                        AND t1a.ReadingDate = rd.Date1
JOIN MeterReadings as t1b ON t1b.EquipmentId = t1a.EquipmentId 
                          AND t1b.ReadingDate = rd.NextReadingDate
order by t1a.EquipmentId, t1a.readingdate

SQL Fiddle I was playing with