需要根据时间列的变化更新 id
Need to update id as per change in time column
我有一个 table 具有以下架构和记录。
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
上面table,第4条记录时差一个小时所以id更新为x11(new),下一次时差小于30分钟所以id保持为x11 和第 6 条记录的差异超过 30 分钟,因此 id 变为 x12。其他ID也一样。
任何人都可以提出建议。
您可以使用累计和 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
您需要使用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))
干杯!!
我有一个 table 具有以下架构和记录。
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
上面table,第4条记录时差一个小时所以id更新为x11(new),下一次时差小于30分钟所以id保持为x11 和第 6 条记录的差异超过 30 分钟,因此 id 变为 x12。其他ID也一样。
任何人都可以提出建议。
您可以使用累计和 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
您需要使用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))
干杯!!