【问题标题】:Creating the SQL script that tracks progress of an object创建跟踪对象进度的 SQL 脚本
【发布时间】:2021-01-03 13:53:09
【问题描述】:

我有一个具有此架构的表:

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 脚本,返回每个水果的每个卡车和桶对的开始和结束日期。预期结果如下:

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

我已尝试通过滞后/超前窗口函数解决此问题,但日期不正确。是否有另一种使用窗口函数解决此问题的方法,还是我必须为此创建子查询?

【问题讨论】:

  • 你呢 group by truck, bucket,选择 min(date) 然后落后/领先?
  • “我已经尝试解决这个问题”在哪里???我们没有看到任何代码。
  • 欢迎来到 Stack Overflow!请拨打tour,阅读what's on-topic hereHow to Ask,并提供minimal reproducible example。 “为我实现此功能”与此站点无关。您必须做出诚实的尝试,然后针对您的算法或技术提出具体问题。

标签: sql subquery window-functions lag lead


【解决方案1】:

我认为你想要聚合和窗口函数:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-10
    相关资源
    最近更新 更多