从SSRS中的同一列中减去时间值

时间:2017-01-21 11:47:56

标签: sql sql-server reporting-services ssrs-2008

我需要从同一列中减去时间值。我已经订购了需要相互减去的值。我会添加一张桌子的照片,所以你有一个大致的想法。现在我需要从数字2中减去数字1,从数字3中减去数字2,....(来自同一车辆)并将其放在名为“消耗”的列中。例如。

作为一个If函数给了我一个错误,我试图去一个案例函数。但现在我得到错误:“为变量赋值的SELECT语句不能与数据检索操作结合。问题代码是CASE函数,直到@lastvalue = AGVLoggingrunstate.starttime。我显然不能把这个数据检索代码中的代码。那么我该如何做呢?我是否需要制作存储过程?欢迎提示。

Declare @lastSN AS nvarchar, @lastValue int;  
SET @lastSN = 'AGV';
SET @lastValue = 0;

SELECT ROW_NUMBER() OVER (ORDER BY AgvLoggingRunstate.vehicle,AgvLoggingRunstate.starttime) AS Row,
  AgvLoggingRunstate.id,
  AgvLoggingRunstate.vehicle,
  AgvLoggingRunstate.node,
  AgvLoggingRunstate.runstate,
  AgvLoggingRunstate.orderclass,
  AgvLoggingRunstate.loaded,
  AgvLoggingRunstate.starttime,
  AgvLoggingRunstate.endtime,
  DATEDIFF(second,AgvLoggingRunstate.starttime,AgvLoggingRunstate.endtime) AS DiffDate,
Case 
WHEN @lastSN = AgvLoggingRunstate.vehicle Then AgvLoggingRunstate.starttime - @lastValue 
ELSE 0 
END AS Consumption,

@lastSN = AgvLoggingRunstate.vehicle,
@lastValue = AgvLoggingRunstate.starttime


FROM  AgvLoggingRunstate

Where AgvLoggingRunstate.starttime > @Startdate and   AgvLoggingRunstate.starttime < @Enddate and AgvLoggingRunstate.runstate = 'Battery'

Order by

AgvLoggingRunstate.vehicle,
AgvLoggingRunstate.starttime

table

答案并添加order by功能后的结果:

enter image description here

现在唯一不正确的答案是两天之间。我需要过滤掉它。 (仍在阅读COALESCE上的所有信息,LEFT JOIN,..因为答案对我来说还不完全清楚)

WITH Times (RowNumber, vehicle, starttime,endtime)
AS
(SELECT ROW_NUMBER() OVER (ORDER BY vehicle, starttime),vehicle, starttime,endtime FROM AgvLoggingRunState WHERE starttime > @Startdate and  starttime < @Enddate and AgvLoggingRunstate.runstate = 'Battery') 

SELECT CurrentTime.Vehicle,
             CurrentTime.StartTime,
             CurrentTime.EndTime, 
             NextTime.StartTime AS NextTime,
             COALESCE(DATEDIFF(SECOND,CurrentTime.StartTime,NextTime.StartTime),0)                      
             AS Seconds,
             COALESCE(DATEDIFF(SECOND,CurrentTime.StartTime,CurrentTime.EndTime),0) 
             AS SecondsDiffEnd
FROM Times CurrentTime
  LEFT OUTER JOIN Times NextTime
  ON CurrentTime.RowNumber +1  = NextTime.RowNumber
  AND CurrentTime.Vehicle = NextTime.Vehicle  

Order by StartTime

1 个答案:

答案 0 :(得分:1)

您已正确使用行号功能。但是,您正尝试使用变量执行连接所需的操作。在下面的示例中,您将看到我如何使用您的行号创建CTE,然后在查询中使用它,加入到下一条记录(只要车辆匹配)。 您需要确定每辆车最后一条记录的正确答案。现在,它是零(参见Coalesce函数) 在使用LEAD的未来版本中,这将非常简单。哦,好吧。

updateBackground