I’ve got a problem that can’t be new, but I can’t figure out how to get the answer I want. It is probably something simple that I’m missing
Using mysql 5.5, I have 2 tables, ‘referrals’ and ‘status’. I want to count referrals that have been cancelled, grouped by appt_date:
SELECT SUM(1) AS count, appt_date FROM referrals
GROUP BY appt_date
JOIN status ON referrals.id=status.referral_id
WHERE status.status_name="cancelled"
This works fine until I have a referral that gets cancelled twice. In other words, a referral with a given id that has 2 rows in the status table with matching referral_id will get counted twice.
How to count each referral record only once when doing the join operation here?
EDIT:
My real question should have been this:
SELECT SUM(quantity) AS count, appt_date FROM referrals
GROUP BY appt_date
JOIN status ON referrals.id=status.referral_id
WHERE status.status_name="cancelled"
since each referral can have its own quantity.
Try changing count to count(DISTINCT id)