创建跟踪对象进度的 SQL 脚本

Creating the SQL script that tracks progress of an object

我有一个 table 具有此架构:

Fruit   Truck ID  Bucket ID        Date         
------   -----    ---------     ----------
Apple      1         101        2018/04/01
Apple      1         101        2018/04/10
Apple      1         112        2018/04/16
Apple      2         782        2018/08/18
Apple      2         782        2018/09/12
Apple      1         113        2019/09/12
Apple      1         113        2019/09/21

我的目标是编写一个 SQL 脚本,其中 returns 每个水果的每对卡车和水桶的开始和结束日期。预期结果如下:

Fruit   Truck ID  Bucket ID     Start Date     End Date     
------   -----    ---------     ----------    ----------
Apple      1         101        2018/04/01    2018/04/16
Apple      1         112        2018/04/16    2018/08/18
Apple      2         782        2018/08/18    2018/09/12
Apple      1         113        2019/09/12    2019/09/21

我尝试通过 lag/lead window 函数解决这个问题,但日期不正确。是否有另一种使用 window 函数解决此问题的方法,或者我是否必须为此创建子查询?

我认为您需要聚合和 window 函数:

select fruit, truck_id, bucket_id,
    min(date) start_date,
    lead(min(date), 1, max(date)) over(partition by fuit order by min(date)) end_date
from mytable
group by fruit, truck_id, bucket_id