0

Estoy intentando agrupar datos de una tabla de oracle 11g, pero con mi query cuando el patron de datos no es continuo no logro obtener el resultado deseado.

Tiempo Pos Estado Fuente
10 7 1 1
11 7 1 1
12 7 0 1
13 7 0 1
14 7 0 1
15 7 1 1
16 7 1 1
17 7 1 1
18 7 1 1
19 7 1 2
20 7 1 2
21 13 1 2
22 13 1 2
23 13 1 2
24 13 1 2
25 19 1 2

De la tabla anterior quiero obtener el siguiente resultado:

T1 T2 Pos Estado Fuente
10 11 7 1 1
12 14 7 0 1
15 18 7 1 1
19 20 7 1 2
21 24 13 1 2

Adjunto captura de pantalla de la tabla y de mi query.

Query:

SELECT
  POS_APILADOR,
  MIN(TO_CHAR(timestamp, 'YYYY-MM-DD HH24:MI:SS')) AS T1,
  MAX(TO_CHAR(timestamp, 'YYYY-MM-DD HH24:MI:SS')) AS T2,
  FUENTE_CHIP,
  ESTADO_APILADOR
FROM RETTIME_WPH1_INSTA
WHERE
  STATUS = 'new'
  AND
  POS_APILADOR NOT IN(
      SELECT POS_APILADOR
      FROM RETTIME_WHP1_INSTA
      WHERE RECORD_TIME = (SELECT MAX(RECORD_TIME) FROM RETTIME_WHP1_INSTA))
 GROUP BY POS_APILADOR, FUENTE_CHIP, ESTADO_APILADOR
 ORDER BY
    TI DESC;

Desde ya muchas gracias.

Tabla origen de los datos

Query y resultado

3
  • Ok, gracias por la sugerencia.
    – aselios
    el 27 jul. 2021 a las 15:00
  • Y q criterio hay q tener en cuenta para que los registros salgan en esa forma q pides
    – Japv
    el 27 jul. 2021 a las 16:48
  • Lo que necesito es obtener el tiempo de inicio y fin, agrupando primero por posicion, luego estado y por ultimo fuente.
    – aselios
    el 27 jul. 2021 a las 17:22

1 respuesta 1

0

Con funciones de ventana. Ordenando dentro de una ventana por tiempo, obtén los valores del registro anterior; cuando alguno de los valores cambia ese será el registro que quieres mostrar, restando únicamente obtener el tiempo final trayendo el tiempo anterior del cambio siguiente.

SELECT r.tiempo
     , lead(r.tiempo_ant) over (order by r.tiempo) tiempo2
     , r.pos
     , r.estado
     , r.fuente
  FROM ( SELECT r.*
              , lag(pos)    over (order by tiempo) pos_ant
              , lag(estado) over (order by tiempo) estado_ant
              , lag(fuente) over (order by tiempo) fuente_ant
              , lag(tiempo) over (order by tiempo) tiempo_ant
           FROM rettime r
       ) r
  WHERE pos <> pos_ant 
     OR estado <> estado_ant 
     OR fuente <> fuente_ant 
     OR tiempo_ant is null
1
  • Gracias por la respuesta. Lo voy a probar y comento.
    – aselios
    el 28 jul. 2021 a las 14:59

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.