SQL merging records based on date range

好久不见. 提交于 2021-02-08 10:52:26

问题


I have a data set representing deliveries made by several vehicles, which can each load and discharge at different locations. I am trying to find out how many vehicles it took to do all deliveries, while grouping/merging all trips that loaded within +- x days. For example:

  • vehicle V1 could load in Zone A (date X) and B (date X+2), and discharge in Zone C and D, that would count as 1 vehicle/trip because it loaded within 2 days.
  • V1 could also simply do Zone A (date Y) to Zone C, that would count 1 trip as well

This is how the raw data looks like:

    Id  LoadArea    LoadDate    Vehicle Discharge Area  Qty
456559  Zone A      15/07/2019   V1     Zone Z          64
408481  Zone B      13/07/2019   V1     Zone X          70
365566  Zone A      12/07/2019   V1     Zone Y          26
244634  Zone C      12/07/2019   V2     Zone X          10
453409  Zone D      10/07/2019   V2     Zone Z          53
183776  Zone A      20/04/2019   V1     Zone Y          13
379698  Zone A      20/04/2019   V1     Zone Z          21
370324  Zone D      28/02/2019   V3     Zone W          39

This is what I am aiming to get to:

LoadArea        LoadDate    Vehicle Qty
Zone A;Zone B   12/07/2019  V1          160
Zone C;ZoneD    10/07/2019  V2          63
Zone A;Zone B   20/04/2019  V1          34
Zone D          28/02/2019  V3          39

The LoadDate returned when merging records that are less than +- X days away would ideally be the earliest one of the records being merged.

Would anyone have an idea how to do this - i've been stuck on this for days now.... Thanks for your help!

来源:https://stackoverflow.com/questions/63059123/sql-merging-records-based-on-date-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!