Skip to content
Advertisement

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
  )

Advertisement

Answer

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';
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement