【问题标题】:How do I take the minimum value from another row in SQL?如何从 SQL 中的另一行获取最小值?
【发布时间】:2021-08-20 05:40:10
【问题描述】:

抱歉,标题有点模棱两可,我不能说得更好了。

我的输出中有以下记录。

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 为 null 时,Station enter_time 也应该为 null,在这种情况下,我希望最早的时间也可以有多个“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
    )

【问题讨论】:

  • 那么,您想要一个简单的选择语句,还是想要更新另一列?

标签: mysql sql amazon-redshift


【解决方案1】:
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

【讨论】:

    【解决方案2】:

    使用窗口函数:

    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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-20
      • 2021-05-09
      • 2022-01-09
      • 2019-03-09
      • 2013-10-13
      • 2016-07-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多