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

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

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

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

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

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

w1jd8yoj1#

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

  1. select
  2. user_id, time, registration time, diff, before_reg,
  3. (diff < 0 and diff = max(diff) over (partition by user_id))
  4. as is_registration_session
  5. from t

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

  1. create index ix1 on t (user_id, diff);

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

  1. update t
  2. set is_registration_session = diff = (
  3. select max(diff) from t x where x.user_id = t.user_id and x.diff < 0
  4. )
展开查看全部

相关问题