Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

180
Views
Ventana de tiempo en PostgreSQL

Soy nuevo en PostgreSQL (específicamente, uso Timescale db) y tengo una pregunta sobre las ventanas de tiempo.

Datos:

 date |customerid|names 2014-01-01|1 |Andrew 2014-01-02|2 |Pete 2014-01-03|2 |Andrew 2014-01-04|2 |Steve 2014-01-05|2 |Stef 2014-01-06|3 |Stef 2014-01-07|1 |Jason 2014-01-08|1 |Jason

La pregunta es: retrocediendo en el tiempo x días (visto desde cada fila), ¿cuántos nombres distintos hay que comparten la misma identificación?

Para x=2 días, el resultado debería verse así:

 date |customerid|names |count 2014-01-01|1 |Andrew |1 2014-01-02|2 |Pete |1 2014-01-03|2 |Andrew |2 2014-01-04|2 |Steve |3 2014-01-05|2 |Stef |3 2014-01-06|3 |Stef |1 2014-01-07|1 |Jason |1 2014-01-08|1 |Jason |1

¿Es esto posible en PostgreSQL sin usar un bucle sobre cada fila?

Información adicional: Los intervalos de tiempo de los datos no son equidistantes en la realidad.

¡Muchos gracias!

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Sería bueno si pudieras usar funciones de ventana:

 select t.*, count(distinct name) over (partition by id order by date range between interval 'x day' preceding and current row ) as cnt_x from t;

Por desgracia, eso no es posible. Entonces puedes usar una unión lateral:

 select t.*, tt.cnt_x from t left join lateral (select count(distinct t2.name) as cnt_x from t t2 where t2.id = t.id and t2.date >= t.date - interval 'x day' and t2.date <= t.date ) tt on true;

Para el rendimiento, desea un índice en (id, date, name) .

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!