Oracle
 sql >> Base de Dados >  >> RDS >> Oracle

Combinação Oracle SQL MIN e MAX da mesma tabela


Para os dados de amostra, o seguinte também funciona
WITH
RawData AS (
  SELECT
    id1
    , jobID
    , message
    , TIMESTAMP_for_start_message timeStamp
    , time_in_seconds
  FROM StartMessageTable
  UNION ALL
  SELECT
    id1
    , jobID
    , message
    , TIMESTAMP_success_msg_received
    , time_in_seconds
  FROM SuccessMessageTable
  ORDER BY id1, jobID, 4
),
Detail AS (
  SELECT
    id1
    , jobID
    , message message1
    , LEAD (message, 1) OVER (ORDER BY id1, jobID, timeStamp) message2
    , timeStamp timeStamp1
    , LEAD (timeStamp, 1) OVER (ORDER BY id1, jobID, timeStamp) timeStamp2
    , time_in_seconds secs1
    , LEAD (time_in_seconds, 1) OVER (ORDER BY id1, jobID, timeStamp) secs2
  FROM RawData
)
SELECT
  id1
  , timeStamp1 TIMESTAMP_for_start_message
  , timeStamp2 TIMESTAMP_for_success_message
  , jobID
  , 'start' msgStart
  , 'success' msgSuccess
  , secs1 start_secs
  , secs2 success_secs
FROM Detail
WHERE (message1 = 'start' AND message2 = 'successful') OR message2 IS NULL
ORDER BY timeStamp1
;

com a mesma ressalva em relação ao primeiro e ao último valor na coluna "start_secs".
SQL Fiddle