1

How can I use a sub query for just the invite table? I'd like all records from patient_profiles and for the invites join to use only records created after a specific date?

SELECT p.first_name,
COUNT(invites.invited_by_id)as invite_count
FROM patient_profiles AS p
LEFT OUTER JOIN patient_profiles AS invites ON invites.invited_by_id = p.id
WHERE p.is_test = false AND AND invites.created_at >= '2017-10-16'::date 
GROUP BY p.first_name    

2 Answers 2

1

You don't need a subquery. Just move the date condition to the ON clause:

SELECT p.first_name,
       COUNT(invites.invited_by_id)as invite_count
FROM patient_profiles p LEFT OUTER JOIN
     patient_profiles invite
     ON invites.invited_by_id = p.id AND invites.created_at >= '2017-10-16'::date
WHERE p.is_test = false
GROUP BY p.first_name;
Sign up to request clarification or add additional context in comments.

Comments

0

You can use HAVING.

SELECT p.first_name, COUNT(invites.invited_by_id)as invite_count
FROM patient_profiles p
GROUP BY p.first_name
HAVING p.is_test = false AND p.created_at >= '2017-10-16'::date 

1 Comment

this appears to filter all records based on the date, I'd only like the records for COUNT() to be filtered based on the date clause

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.