Итак, во-первых, UNION ALL
записи из Table1
и Table2
, а затем выполняйте вычисления и соединяйте их в другом месте, что-то вроде:
SELECT usrs.uid as "user's ID"
, usrs.first_name as "First Name"
, usrs.last_name as "Last Name"
, both_systems.task_started_ts as "start_gmt_ts" //<-- I'd like to use the next val if previous end was null
, both_systems.task_ended_ts as "end_gmt_ts" //<-- This ts may be null
, both_systems.task_desc_cd as "task"
, (extract(day from (both_systems.task_ended_ts - both_systems.task_started_ts DAY(4) TO SECOND)) * 86400) +
(extract(hour from (both_systems.task_ended_ts - both_systems.task_started_ts DAY(4) TO SECOND)) * 3600) +
(extract(minute from (both_systems.task_ended_ts - both_systems.task_started_ts DAY(4) TO SECOND)) * 60) +
extract(second from (both_systems.task_ended_ts - both_systems.task_started_ts DAY(4) TO SECOND))
as duration_secs
, both_systems.task_created_ts as "created_at",
, both_systems.task_created_date as "reporting date"
FROM (-- Select as many columns as you need, just make sure columns are the same between both tables
SELECT '1' AS system_in_use, c.task_started_ts, c.task_ended_ts, c.task_desc_code, c.users_db_id , c.total_time_seconds, c.task_created_ts, c.task_created_date, c.date
FROM foo.Table1 c
UNION ALL
SELECT '2' AS system_in_use, c.task_started_ts, c.task_ended_ts, c.task_desc_code, c.users_db_id , c.total_time_seconds, c.task_created_ts, c.task_created_date, c.date
FROM bar.Table2 c) both_systems
JOIN baz.Table3 usrs
ON usrs.users_db_id = c.both_systems
-- not sure where date column is coming from, I presume task
-- hint: never use non-qualified column names in multi-table queries
AND both_systems.date BETWEEN usrs.role_start AND usrs.role_end
WHERE both_systems.task_created_date >= '2019-03-15'
AND usrs.uid in ('42')
Теперь об использовании даты начала следующей задачив качестве даты окончания в случае, если дата окончания текущей задачи равна NULL, используйте LEAD
.Что-то вроде:
COALESCE(both_systems.task_ended_ts, LEAD(both_systems.task_started_ts IGNORE NULLS, 1, 0) OVER (PARTITION BY usrs.uid ORDER BY both_systems.task_started_ts)) AS task_ended_ts
Итак, сначала возьмите tasks_ended_ts
и только если это NULL
, найдите следующую строку, используя LEAD
.
Возможно, вам понадобится другой подзапрос, еслиВы также хотите рассчитать duration_secs
по этой формуле.