簡體   English   中英

SQL:選擇最近的日期時間行以及特定的列值

[英]SQL : Select the nearest datetime row along with specific column value

我有下表

       Date                    Vehicle_ID          Status     
01/01/2020 5:00 PM                X500              Ready
01/01/2020 6:00 PM                X500              Ready
01/01/2020 7:15 PM                X500              Ready
01/01/2020 8:00 PM                X500              Service
01/01/2020 5:00 PM                X500              Ready
01/01/2020 4:00 PM                X670              Ready
01/01/2020 4.30 PM                X670              Ready
01/01/2020 8:00 PM                X670              Ready
01/01/2020 9:30 PM                X670              Service
01/01/2020 5:00 PM                X670              Ready

我需要對具有服務的行和在服務后立即准備就緒的發送記錄進行子集化。

我想要的輸出是

       Date                    Vehicle_ID          Status  
01/01/2020 7:15 PM                X500              Ready
01/01/2020 8:00 PM                X500              Service
01/01/2020 8:00 PM                X670              Ready
01/01/2020 9:30 PM                X670              Service

我正在努力編寫過濾這些記錄的條件。 請幫我

一種方法使用lead() / lag()

select date, vehicle_id, status
from (select t.*,
             lag(status) over (partition by vehicle_id order by date) as prev_status,
             lead(status) over (partition by vehicle_id order by date) as next_status
     from t
    ) t
where (status = 'Ready' and next_status = 'Service') or
      (prev_status = 'Ready' and status = 'Service')

根據您的結果,您需要 status = 'Service' 和之前的行:

with cte as 
 ( 
   select t.*
      -- next row's status
      ,lead(status)
       over (partition by vehicle_id
             order by date) as next_status
   from tab as t
 )
select date, vehicle_id, status
from cte
where status = 'Service'      -- rows that had service
   or next_status = 'Service' -- row before service

順便說一句,當您在服務立即編寫就緒時,我希望得到以下行,而不是前一行。 為此,您可能會切換到 LAG 而不是 LEAD。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM