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

191
Views
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 answers
Answer question

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 Report

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 Report

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 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!