Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

190
Vistas
PostgreSQL Query To Obtain Value that Occurs more than once in 12 months

I have the following query to return the number of users that booked a flight at least twice, but I need to identify those which have booked a flight more than once in the range of 12 months

SELECT COUNT(*)
FROM sales
WHERE customer in
  (
    SELECT customer
    FROM sales
    GROUP BY customer
    HAVING COUNT(*) > 1
  )
over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

You would use window functions. The simplest method is lag():

select count(distinct customer)
from (select s.*,
             lag(date) over (partition by customer order by date) as prev_date
      from sales s
     ) s
where prev_date > s.date - interval '12 month';
over 4 years ago · Santiago Trujillo Denunciar

0

At the cost of a self-join, @AdrianKlaver's answer can adapt to any 12-month period.

SELECT COUNT(DISTINCT customer) FROM 
   (SELECT customer 
    FROM sales s1
    JOIN sales s2 
    ON s1.customer = s2.customer
         AND s1.ticket_id <> s2.ticket_id
         AND s2.date_field BETWEEN s1.date_field AND (s1.date_field + interval'1 year')
    GROUP BY customer
    HAVING COUNT(*) > 1) AS subquery;
over 4 years ago · Santiago Trujillo Denunciar

0

A stab at it with a made up date field:

SELECT COUNT(*)
FROM sales
WHERE customer in
  (
    SELECT customer
    FROM sales
    WHERE date_field BETWEEN '01/01/2019' AND '12/31/2019'
    GROUP BY customer
    HAVING COUNT(*) > 1
  )
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda