如何为不同键设置具有最小值的行属性

w46czmvw  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(332)

我有一张这样的table(不好,但需要放在这里):

Sessions

    user_id | time  | registration time | diff | before_reg |is_registration_session
       1    | 00:10 |       00:30       | -20  |     True   |   Null
       1    | 00:20 |       00:30       | -10  |     True   |   Null
       1    | 00:27 |       00:30       | -3   |     True   |   Null
       1    | 00:31 |       00:30       |  1   |     False  |   Null
       2    | 00:14 |       00:20       | -6   |     True   |   Null
       2    | 00:26 |       00:20       |  6   |     False  |   Null

我想要实现的是:我想要找到最小(最大负数)的行 reg_diff 对于每个 user_id 并在列中设置值 is_registration_sessionTrue . 我做这件事的唯一方法是在python中用“update/set”进行for循环,它需要很多时间。

Sessions

    user_id | time  | registration time | diff | before_reg |is_registration_session
       1    | 00:10 |       00:30       | -20  |     True   |   False
       1    | 00:20 |       00:30       | -10  |     True   |   False
       1    | 00:27 |       00:30       | -3   |     True   |   True
       1    | 00:31 |       00:30       |  1   |     False  |   False
       2    | 00:14 |       00:20       | -6   |     True   |   True
       2    | 00:26 |       00:20       |  6   |     False  |   False
w1jd8yoj

w1jd8yoj1#

您可以使用窗口函数来解决此问题。例如:

select
  user_id, time, registration time, diff, before_reg,
  (diff < 0 and diff = max(diff) over (partition by user_id))
    as is_registration_session
from t

为了获得更好的性能,可以添加索引:

create index ix1 on t (user_id, diff);

编辑以更新列
我误解了你的问题。如果要更新现有列,可以执行以下操作:

update t 
set is_registration_session = diff = (
  select max(diff) from t x where x.user_id = t.user_id and x.diff < 0
)

相关问题