sql >> Base de Datos >  >> RDS >> Mysql

Bigquery:busca varias tablas y agrega con first_seen y last_seen

Primero uniría las tablas (en BigQuery, la sintaxis para unión es coma). Entonces hay dos enfoques:

  1. Utilice funciones analíticas FIRST_VALUE y LAST_VALUE.
SELECT id, timestamp_first, timestamp_last, data FROM
(SELECT 
  id,
  timestamp,
  FIRST_VALUE(timestamp) OVER(
    PARTITION BY id
    ORDER BY timestamp ASC
    ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
  AS timestamp_first,
  LAST_VALUE(timestamp) OVER(
    PARTITION BY id
    ORDER BY timestamp ASC
    ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
  AS timestamp_last
FROM table1, table2, table3
  1. Utilice la agregación MIN/MAX en la marca de tiempo para encontrar primero/último y luego vuelva a unirse a las mismas tablas.
SELECT a.id id, timestamp_first, timestamp_last, data FROM
(SELECT id, data FROM table1,table2,table3) a
INNER JOIN
(SELECT 
   id, 
   MIN(timestamp) timestamp_first,
   MAX(timestamp) timestamp_last 
 FROM table1,table2,table3 GROUP BY id) b
ON a.id = b.id