Home > Enterprise >  How to calculate the value in different row but same column and group it in sql
How to calculate the value in different row but same column and group it in sql

Time:09-12

I would like to calculate how many minutes the type is running. The process will calculate every hour. But if on that hour got many types running, I want to know how many minutes for that process, when to start, and when the type is the end.

Based on the table below, if I got a different type within that hour, I want to know what time type A start and stops, then type B what time start and Ends. After type A end, what time can type A continue to start back :

Type Start Result
A 2:02
A 2:10
A 2:17 2:00 - 2:30
B 2:30 2:30 - 2:46
A 2:46 2:46 - 3:00
A 3:00 3:00 - 4:00
A 4:00 4:00 - 5:00

Final table will show like this:

Type Start Result
A 2:02 2:00 - 2:30
B 2:30 2:30 - 2:46
A 2:46 2:46 - 3:00

Does anyone know how to get do it using SQL query? Thanks in advance.

CodePudding user response:

select   "Type" 
        ,"Start"
        ,case when lead("Start") over(order by "Start") is null then concat(running_min, '-', 'end') else concat(running_min, '-', lead("Start") over(order by "Start")) end as Result
from    (
         select   "Type"    
                 ,"Start"
                 ,min("Start") over(partition by change_count order by "Start") as running_min
         from    (
                  select  "Type"    
                         ,"Start"
                         ,count(change) over(order by "Start") as change_count
                  from   (
                          select *
                                 ,case when "Type" <> lag("Type") over(order by "Start") then 1 end as change 
                          from t
                         ) t
                  ) t
         ) t
Type Start result
A 02:02:00 02:02:00-02:10:00
A 02:10:00 02:02:00-02:17:00
A 02:17:00 02:02:00-02:30:00
B 02:30:00 02:30:00-02:46:00
A 02:46:00 02:46:00-03:00:00
A 03:00:00 02:46:00-04:00:00
A 04:00:00 02:46:00-end

Fiddle

  •  Tags:  
  • sql
  • Related