下面描述了我想对这张表做些什么
左边是一张表,我希望为每个事件计算'current_value'
代码1将current_value重置为值
代码2为current_value增加值
Code3使用值
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也有这个问题。
任何帮助,这里的错误将不胜感激。
答案 0 :(得分:0)
我不确定我是否100%理解你的问题,但如果我正确地阅读了这些内容,你应该只需要对外表进行别名:
Select
t.EventId,
t.DeviceId,
(select last(value) from Events as E where E.EventCode = 1 and E.DeviceID = t.DeviceID and E.EventId<t.EventId) AS LastSetValue,
(select last(value) from Events as E where E.EventCode = 1 and E.DeviceID = t.DeviceID and E.EventId<t.EventId) AS FromEventID,
(select sum(value) from Events as E where E.EventCode = 2 and E.DeviceID = t.DeviceID and E.EventId between fromEventId and t.EventId) AS SumOfAdded,
(select sum(value) from Events as E where E.EventCode = 3 and E.DeviceID = t.DeviceID and E.EventId between FromEventId and t.EventId) AS SumOfSubtracted,
LastSetValue+SumOfAdded-SumofSubtracted as current_value
from Events t;