我正在尝试选择一个带有子查询的查询,该子查询选择两个时间戳字段之间的增量。
例如Delta =时间戳N-时间戳N-1
{{1}}
这是我得到的错误:
信息512,级别16,状态1,第1行
子查询返回的值超过1。当子查询遵循=,!=,<,<=,>,> =或将子查询用作表达式时,不允许这样做。
答案 0 :(得分:1)
您可以为此使用lag()函数
select T_event.Actie_ID, actie_omschrijving, event_timestamp, left(custom1,4) as model, custom1, Custom2,
Lag(T_event.event_timestamp) over (order by T_event.Event_ID) - T_event.event_timestamp AS Delta
from T_event
inner join T_Actie ON T_event.Actie_ID = T_Actie.Actie_ID
WHERE T_EVENT.Actie_ID in (48,49,43,31,36)
and Event_Timestamp >= '2019-07-22'
order by Event_timestamp DESC
答案 1 :(得分:0)
您的子查询返回多个值。您必须使用TOP子句或应用适当的过滤条件,以确保该子查询仅返回一行。当您应用TOP时,请确保您正在应用正确的ORDER BY子句。
select TOP 1 datediff(day,B.event_timestamp, A.event_timestamp) AS timediff
from t_event A,
t_event B
where B.Event_ID = A.Event_ID-1
ORDER BY timediff
另一件事,我从您的查询中发现的是,您计算出的时间戳差异与外部查询无关。您必须使用外部查询EventID
select T_event.Actie_ID, actie_omschrijving, event_timestamp, left(custom1,4) as model, custom1, Custom2,
(select TOP 1 datediff(day,B.event_timestamp, outer.event_timestamp) as timediff
from t_event AS B
where outer.Event_ID = A.Event_ID-1
ORDER BY timediff) as timestampdifference
from T_event as outer
inner join T_Actie ON T_event.Actie_ID = T_Actie.Actie_ID
WHERE T_EVENT.Actie_ID in (48,49,43,31,36)
and Event_Timestamp >= '2019-07-22'
order by Event_timestamp DESC
答案 2 :(得分:0)
实际上,您的内部子查询与外部查询无关,因此,每行输出n个行,这是不可接受的。因此,您查询的可能解决方案是:
select t.T_event.Actie_ID, t.actie_omschrijving, t.event_timestamp, left(t.custom1,4) as model, t.custom1, t.Custom2,
(select B.event_timestamp - A.event_timestamp
from t_event A,
t_event B
where B.Event_ID = A.Event_ID-1
and B.Event_ID=t.Event_ID) ---- here it might be A.event_id.... depends on your input and expected output
from T_event as t
inner join T_Actie ON t.Actie_ID = T_Actie.Actie_ID
WHERE t.Actie_ID in (48,49,43,31,36)
and Event_Timestamp >= '2019-07-22'
order by Event_timestamp DESC