我有一个包含以下模式和记录的表。
id use_time
x1 10.01
x1 10.02
x1 10.04
x1 11.09
x1 11.23
x1 12.08
x2 01.01
x2 01.04
x2 01.23
x2 03.44
x2 04.31
每当use_time之间的差异超过30分钟时,我就需要更新id。这就是说,对于每30分钟,id应该是唯一的。
新行应该如下所示
id use_time
x1 10.01
x1 10.02
x1 10.04
x11 11.09
x11 11.23
x12 12.08
x2 1.01
x2 1.04
x2 1.23
x21 3.44
x23 4.31
在上表中,在第4条记录中,时间差为1小时,因此id被更新为x11 (新的),并且下一次时间差小于30分钟,因此id停留在x11,并且在第6条记录中,时间差超过30分钟,因此id变为x12。对于其他ids也是如此。
有没有人可以建议。
发布于 2019-09-12 10:13:51
您需要按如下方式使用lag
和sum
解析函数:
SELECT ID || CASE WHEN S > 0 THEN S END AS NEW_ID,
USE_TIME FROM
(select ID,
use_time,
sum(diff) over (partition by id order by use_time) S
from
(select id, use_time,
case when (use_time - lag(use_time)
over (partition by id order by use_time)) * 24 * 60 > 30
then 1 else 0 end as diff
from your_table))
干杯!!
发布于 2019-09-12 06:17:06
您可以使用累积和和lag()
select id || (case when sum(is_change) over (partition by id order by use_time) > 0
then sum(is_change) over (partition by id order by use_time)
end),
use_time
from (select t.*,
(case when lag(use_time over (partition by id order by use_time) < use_time
then 1 else 0
end) as is_change
from t
) t
https://stackoverflow.com/questions/57897469
复制相似问题