简体   繁体   English

Oracle SQL:根据多个行条件拆分组

[英]Oracle SQL: Splitting a group by based on multiple rows criteria

I have data where a single address can have multiple journeys, something like this: 我有一个地址可以有多个旅程的数据,如下所示:

在此处输入图片说明

I want to split the address by each journey ("Start of Journey" to "End of Journey" and all "Part of Journeys" in the middle constitute one Journey) and aggregate the costs, so each address can have multiple rows based on the number of journeys, something like this: 我想按每次旅程划分地址(“旅程的开始”到“旅程的结束”,中间的所有“旅程的一部分”构成一个旅程)并汇总费用,因此每个地址可以根据旅行次数,如下所示:

在此处输入图片说明

I just can't seem to figure out the logic that I would need to use to solve this. 我似乎无法弄清楚解决此问题所需的逻辑。 Any help or pointers would be highly appreciated. 任何帮助或指针将不胜感激。

Use a running sum to tag rows into groups, starting a new number whenever Start of Journey row is encountered for a given address. 使用一个连续的总和将行标记为组,每当给定地址遇到Start of Journey起点行时,就开始一个新的数字。 Then use it to group and get the total cost. 然后使用它进行分组并获得总成本。

select address,sum(cost) 
from (select t.*
      --Replace OrderCol with a column that specifies row order
      ,sum(case when journey='Start of Journey' then 1 else 0 end) over(partition by address order by OrderCol) as grp 
      from tbl
     ) t
group by address,grp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM