下面描述了我想用这个表做什么 左边是一个表,我想从中计算每个事件的“current_value”
代码 1 将 current_value 重置为 value
代码 2 将 value 添加到 current_value
Code3 用 value 减少 current_value
Table Events |column to be calculated
eventId deviceId EventCode value |current_value
1 1 1 2 |2
2 1 2 1 |3
3 1 2 1 |4
4 1 2 1 |5
5 1 3 2 |3
6 1 2 2 |5
7 1 1 1 |1
8 1 2 2 |3 code 1: set
9 1 2 1 |4 code 2: add
10 1 2 1 |5 code 3: subtract
11 1 3 3 |2
我的 SQL 代码看起来像
Select
EventId,
deviceId,
(select last(value) from Events as E where E.EventCode = 1 and E.DeviceID = DeviceID and E.EventId<EventId) AS LastSetValue,
(select last(value) from Events as E where E.EventCode = 1 and E.DeviceID = DeviceID and E.EventId<EventId) AS FromEventID,
(select sum(value) from Events as E where E.EventCode = 2 and E.DeviceID = DeviceID and E.EventId between fromEventId and EventId) AS SumOfAdded,
(select sum(value) from Events as E where E.EventCode = 3 and E.DeviceID = DeviceID and E.EventId betweein FromEventId and EventId) AS SumOfSubtracted,
LastSetValue+SumOfAdded-SumofSubtracted as current_value
from Events;
此代码似乎不起作用,因为在子选择部分 DeviceID 看起来是内部临时表 DeviceID,当我为外部 DeviceID 设置别名时,这也不起作用,因为找不到它。从EventID也有这个问题。
任何帮助这里有什么问题将不胜感激。