Прогон: https://www.db -fiddle.com / f / iDtVPvCnXV6E92CzyWNjWK / 0
Нажмите прогон там, чтобы увидеть результат 11 строк.
SQL:
with source as (
select AccesID, OwnerAccessID, null RobotID, StartTime, EndTime, Success from Source_Base union
select AccesID, OwnerAccessID, RobotID, StartTime, EndTime, Success from Source_Robot
)
select AccesID,OwnerAccessID, RobotID, Success,
(select ExceptionID from Robot_Exception e where e.OwnerAccessID=source.AccesID) Exception,
round(extract(epoch from EndTime)-extract(epoch from StartTime)) duration,
starttime
from source
order by StartTime;
С таблицами образцов:
create table source_base ( accesid numeric, owneraccessid numeric, starttime timestamp, endtime timestamp, success numeric );
insert into source_base values
(1248683283, 0, '2019-04-10 09:10:23.237', '2019-04-10 09:10:26.727', 0),
(1248683284, 10013553, '2019-04-10 09:10:23.233', '2019-04-10 09:12:05.703', 1),
(1248683285, 0, '2019-04-10 14:24:32.037', '2019-04-10 14:24:39.313', 0),
(1248683286, 10013555, '2019-04-10 14:24:32.030', '2019-04-10 14:25:42.387', 1),
(1248683287, 0, '2019-04-10 14:44:47.747', '2019-04-10 14:44:50.973', 1),
(1248683288, 1248683287, '2019-04-10 14:44:47.747', '2019-04-10 14:44:51.697', 1);
create table source_robot ( accesid numeric, owneraccessid numeric, robotid numeric, starttime timestamp, endtime timestamp, success numeric );
insert into source_robot values
(10013551, 1248683283, 11, '2019-04-10 09:10:27.587', '2019-04-10 09:11:17.605', 0),
(10013552, 10013551, 12, '2019-04-10 09:11:18.186', '2019-04-10 09:11:18.219', 0),
(10013553, 10013552, 13, '2019-04-10 09:11:18.323', '2019-04-10 09:12:05.003', 1),
(10013554, 1248683285, 15, '2019-04-10 14:24:41.763', '2019-04-10 14:25:36.313', 0),
(10013555, 10013554, 14, '2019-04-10 14:25:37.393', '2019-04-10 14:25:39.967', 1);
create table robot_exception (exceptionid numeric, owneraccessid numeric, robotid numeric, starttime timestamp, endtime timestamp);
insert into robot_exception values
(999993, 10013554, 15, '2019-04-10 14:24:41.763', '2019-04-10 14:25:36.313'),
(999992, 10013552, 12, '2019-04-10 09:11:18.189', '2019-04-10 09:11:18.217'),
(999991, 10013551, 11, '2019-04-10 09:10:27.593', '2019-04-10 09:11:17.603');