Sql 引用子选择之外的别名
下面描述了我想对该表执行的操作 左边是一个表格,我想计算每个事件的“当前值” 代码1将当前_值重置为默认值 代码2将值添加到当前值 代码3使用值减少当前的_值Sql 引用子选择之外的别名,sql,scope,alias,calculated-columns,Sql,Scope,Alias,Calculated Columns,下面描述了我想对该表执行的操作 左边是一个表格,我想计算每个事件的“当前值” 代码1将当前_值重置为默认值 代码2将值添加到当前值 代码3使用值减少当前的_值 Table Events |column to be calculated eventId deviceId EventCode 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时,这也将不起作用,因为找不到它。From EventID也有这个问题
如果您能帮我解决问题,我们将不胜感激。我不确定我是否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;
你能不用代码描述当前值代表什么吗?当前值是设备在被测量时的长度。eventID链接到日期或时间。它是初始值加上附加长度的集合,有时从设备中减少零件。有时整个设备被替换为一个新的设备,重新开始使用一个新的初始值;我应该把别名放在哪里?@hbl-就在事件和内部连接之间,就像事件t内部连接。。。