如何从 SQL 中的另一行中取最小值?

How do I take the minimum value from another row in SQL?

很抱歉标题含糊不清,我无法用更好的方式表达它。

我的输出中有以下记录。

route_id date employee_id stop_type vehicle_stop_number enter_time
1 2021-06-16 ABC Pickup 1 2021-06-16 15:06:39.000000
1 2021-06-16 ABC Pickup 2 2021-06-16 15:27:35.000000
1 2021-06-16 ABC Dropoff 3 2021-06-16 16:36:42.000000
1 2021-06-16 ABC Station 0 null

我想要的是在 stop_type = 'Dropoff' 时基本上得到 min(enter_time) 并将其粘贴到 'Station' 行

route_id date employee_id stop_type vehicle_stop_number enter_time_actuals
1 2021-06-16 ABC Pickup 1 2021-06-16 15:06:39.000000
1 2021-06-16 ABC Pickup 2 2021-06-16 15:27:35.000000
1 2021-06-16 ABC Dropoff 3 2021-06-16 16:36:42.000000
1 2021-06-16 ABC Station 0 2021-06-16 16:36:42.000000

一些极端情况是,当 Dropoff enter_time 为空时,Station enter_time 也应该为空,也可以有多个 'Dropoff' 在这种情况下我想要最早的时间.

这是我一直在尝试的:

SELECT *
    , CASE
          WHEN stop_type = 'Dropoff'
              THEN MIN(enter_time)
                   OVER (PARTITION BY date, route_id, employee_id, stop_type, vehicle_stop_number)
          ELSE null END as min_dropoff_enter_time
    , CASE
          WHEN (stop_type = 'Station' and enter_time is null)
              THEN min_dropoff_enter_time
          ELSE enter_time END as enter_time_updated
FROM
    (
        SELECT * FROM stops
    )
Select route_id, employee_id, stop_type, vehicle_stop_number,
        case when enter_time is null and stop_type ='Station' then
        (select min(enter_time) from stops where s.route_id = route_id and stop_type = 'Dropoff') 
        else enter_time end
        as enter_time_actuals
from stops s

使用window函数:

select s.*,
       (case when stop_type = 'Station'
             then min(case when stop_type = 'Dropoff' then enter_time end) over (partition by route_id) 
             else enter_time
        end) as imputed_enter_time
from stops s;