我有下表:
ID DESCRIPTION TIMESTAMP
1 RECEIVER 00:10:00
1 SENDER 00:08:00
1 EXECUTOR 00:05:00
1 SENDER 00:03:00
如何获取最新“ SENDER”描述,并使用我的时间戳找到另一个描述的时差?
我想找到SENDER和EXECUTOR之间的时差,但由于它同时拾取了SENDER和SENDER项,因此我得到了奇怪的结果。
谢谢 亚当
答案 0 :(得分:2)
SELECT
t1.timestamp - t2.timestamp
from
(SELECT
timestamp
FROM
table
WHERE
description='SENDER'
ORDER BY timestamp DESC LIMIT 1) t1,
table t2
WHERE
t2.description = 'your_description'
答案 1 :(得分:2)
您可以通过使用lag
和row_number
函数来使用这样的机制:
select id, timestamp_diff
from
(
with t(ID,DESCRIPTION,TIMESTAMP) as
(
select 1,'RECEIVER',to_timestamp('00:10:00','HH24:MI:SS') from dual union all
select 1,'SENDER',to_timestamp('00:08:00','HH24:MI:SS') from dual union all
select 1,'EXECUTOR',to_timestamp('00:05:00','HH24:MI:SS') from dual union all
select 1,'SENDER',to_timestamp('00:03:00','HH24:MI:SS') from dual
)
select t.id,
t.timestamp - lag(t.timestamp) over (order by t.timestamp desc) as timestamp_diff,
row_number() over (order by t.timestamp) as rn
from t
where t.description = 'SENDER'
)
where rn = 1;
ID TIMESTAMP_DIFF
-- --------------------
1 -000000000 00:05:00
对于多个ID,请考虑使用以下ID:
select id , max(timestamp_diff) as timestamp_diff
from
(
with t(ID,DESCRIPTION,TIMESTAMP) as
(
select 1,'RECEIVER',to_timestamp('00:10:00','HH24:MI:SS') from dual union all
select 1,'SENDER',to_timestamp('00:08:00','HH24:MI:SS') from dual union all
select 1,'EXECUTOR',to_timestamp('00:05:00','HH24:MI:SS') from dual union all
select 1,'SENDER',to_timestamp('00:03:00','HH24:MI:SS') from dual union all
select 2,'SENDER',to_timestamp('00:06:00','HH24:MI:SS') from dual union all
select 2,'SENDER',to_timestamp('00:02:00','HH24:MI:SS') from dual
)
select t.id,
t.timestamp - lag(t.timestamp) over
(partition by t.id order by t.id,t.timestamp desc) as timestamp_diff,
row_number() over (order by t.id,t.timestamp) as rn,
t.description
from t
where t.description = 'SENDER'
)
group by id, description;
ID TIMESTAMP_DIFF
-- --------------------
1 -000000000 00:05:00
2 -000000000 00:04:00