Mysql
 sql >> Base de Dados >  >> RDS >> Mysql

Bigquery:pesquise várias tabelas e agregue com first_seen e last_seen


Eu primeiro uniria as tabelas (no BigQuery a sintaxe para união é vírgula). Existem então duas abordagens:
  1. Use as funções analíticas FIRST_VALUE e 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. Use a agregação MIN/MAX no carimbo de data/hora para encontrar o primeiro/último e, em seguida, junte-se novamente às mesmas tabelas.
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