1

I have a table for persons and other for visits. I need to count the visits for the month only if it was the first one. So basically get a count of visits for the month but only if your visit for the month, was the first.

Example:

PEOPLE:
   id   
---------
   20   
   30   
   23   

VISITS
  id     |   date
-------------------------
  20     |   09-20-2019
  20     |   10-01-2019
  23     |   10-09-2019
  30     |   10-07-2019

I want to know the coutning only if its the first one, on this example, the counting should equal to 2 because person with ID 20 had a past visit last month.

This is what I have so far on my query

SELECT * FROM visits
LEFT JOIN people ON visits.id = people.id
WHERE date_trunc('month', current_date) <= visits.visit_date AND visits.visit_date < date_trunc('month', current_date) + INTERVAL '1 month'

This is just giving me the visits for the month. How can I filter by only if the person doesnt have past visits.

1
  • 1 is 1. What difference does it make if the visit that gets counted is the first, the last, or the one in the middle? Sounds like you want count(distinct people.id) Commented Oct 24, 2019 at 23:41

2 Answers 2

1

You can simplify the condition by just comparing months. Add not exists to check whether the person had a visit before the current month.

select * 
from visits
left join people on visits.id = people.id
where date_trunc('month', current_date) = date_trunc('month', visits.visit_date)
and not exists (
    select from visits
    where id = people.id
    and date_trunc('month', current_date) > date_trunc('month', visits.visit_date)
    )
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you this helped me a lot!! :)
0

from what I understand on your requirement you just need to get the person Ids that had previous visit.

my proposal is to use dense_rank() to based on date_trunc('month', visit_date)

select v.id from visits v
inner join 
  (select dense_rank() over (partition by date_trunc('month', visit_date) order by visit_date) as rn
  , *
  from visits) t1 on t1.id = v.id
group by v.id, t1.rn
having count(v.id) > 1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.