如何获取两个重叠时间戳的总持续时间并按天分组?

时间:2019-07-18 08:46:20

标签: postgresql timestamp

我有两组日期时间戳记,并且要求两者之间有重叠分钟。在某些情况下,结束日期可能会在第二天。

Table_A
======= 
ID   ,Start_Time _A    , End_Time_A
=======
A   ,03-02-2019 22:30   ,03-02-2019 22:43
A   ,03-02-2019 22:44   ,04-02-2019 03:41
Table_B 
======= 
ID  ,Start_Time _B      ,End_Time_B
=======
A   ,03-02-2019 22:30   ,03-02-2019 23:30
A   ,03-02-2019 23:31   ,04-02-2019 01:45

需要以下输出-

ID, Date    ,Overlap Minutes
=
A   ,03-02-2019 ,42
A   ,04-02-2019 ,105
create table Overlap as
SELECT DISTINCT T2.ID, (cast([Start_time_A] as date)) as Date,
(T1.Start_time_A < T2.End_time_B    and T2.Start_time_B < T1.End_time_A 
and datediff(m, greatest(T1.Start_time_A, T2.Start_time_B), 
least(T1.End_time_A, T2.End_time_B))) as overlap,
(extract(minute from End_time_A - Start_time_A)) as a,
(extract(minute from End_time_A - Start_time_B)) as b,
(extract(minute from End_time_B -  Start_time_B)) as c,
(extract(minute from End_time_B -  Start_time_A)) as d
FROM table_A T1
INNER JOIN table_B T2 ON T1.ID = T2.ID and cast([Start_time_A] as date)= 
cast([Start_time_B] as date)
where overlap='true'
order by Start_time_A;

0 个答案:

没有答案