SQL ||计算每个城市的时间花费(字段)

时间:2021-04-04 05:37:04

标签: sql oracle

我陷入了需要计算在特定城市花费的时间的情况。 这里我有三列:

  1. 时间 -- 当前移动到特定城市的时间
  2. Add_City -- 当前城市
  3. Remove_City -- 从前一个城市移出

Time         Add_City    Remove_City
2021-03-21 12:40:00 Null        Null
2021-03-21 12:45:00 A       B
2021-03-21 14:07:00 Null        Null
2021-03-21 15:32:00 B       A
2021-03-21 19:51:00 Null        Null
2021-03-21 20:10:00 A       B

所以整个场景就像,让我们举个例子:

2021-03-21 12:40:00  Null        Null
2021-03-21 12:45:00 A       B

在第一行,因为在添加和删除城市中没有提到任何内容,这意味着人还没有从一个移动到另一个。 现在进入第二行,因为它表明它从 B 移动到 A,因此当前时间是 A,而它从 2021-03-21 12:40:00 到 2021-03-21 12:45:00 停留在 B。< /p>

我必须计算在每个城市花费的总时间。

1 个答案:

答案 0 :(得分:1)

首先让我们创建示例数据。您应该通过以下方式将其提供给我们:

alter session set nls_date_format = 'dd-mm-yyyy hh24:mi';

create table sample_data (time, add_city, remove_city) as
    select to_date('21-03-2021 12:40'), null, null from dual union all
    select to_date('21-03-2021 12:45'), 'A' , 'B'  from dual union all
    select to_date('21-03-2021 14:07'), null, null from dual union all
    select to_date('21-03-2021 15:32'), 'B' , 'A'  from dual union all
    select to_date('21-03-2021 19:51'), null, null from dual union all
    select to_date('21-03-2021 20:10'), 'A' , 'B'  from dual
;

然后,如果我正确理解了问题,这里是解决问题的一种方法。我假设您希望“在每个城市花费的时间”显示为 interval day to second;如果您只需要“天”(作为十进制数),只需在外部查询中使用 sum(duration)

with
  prep (duration, city) as (
    select lead(time) over (order by time) - time,
           nvl(last_value (add_city    ignore nulls) over (order by time),
               first_value(remove_city ignore nulls) over (order by time
                           rows  between current row and unbounded following))
    from   sample_data
  )
select city, numtodsinterval(sum(duration), 'day') as time_in_city
from   prep
group  by city
order  by city
;

CITY TIME_IN_CITY       
---- -------------------
A    +00 02:47:00.000000
B    +00 04:43:00.000000