Trying to get a simple COUNT from a table that takes a couple of joins and some math. I can’t get it right. I keep running into “invalid use of group function.” In a similar query I get get all the data, just can’t get a count.
I have 4 tables.
CUSTOMERS
id name thegroup periodicity
1 Foo 3 4
GROUPS
id group_name
3 New York
Each customer has a series of pickup dates.
COLLECTIONS
id coll_date customer_id
3 2011-09-07 1
3 2011-07-21 1
And a periods table which is the number of weeks between scheduled pickups.
PERIODS
id duration
4 4
So a duration of 4 means pickup every 4 weeks, or 28 days.
I can calculate when the next pickup date is getting close: If they have a periodicity of 28 days, then when it has been 21 days since the last pickup it is time to flag it. In that case it would be 75% through its periodicity 21/28, or:
(ABS(DATEDIFF(MAX(collections.coll_date), NOW())) / (periods.duration *7))
If that result is greater than .75, then they are due for a pick up.
I can loop through customers and calculate that no problem.
My goal is:
I need to know how many customers in each group are due for pick up, re: COUNT(customers) WHERE (this calculation) > .75 GROUP BY group.id.
I have this so far, but can’t get it right.
SELECT COUNT(*), groups.id
FROM customers
INNER JOIN groups ON customers.thegroup = groups.id
INNER JOIN periods ON customers.periodicity = periods.id
LEFT JOIN collections ON customers.id = collections.rest_id
WHERE status = 1 AND (ABS(DATEDIFF(MAX(collections.coll_date), NOW()))/(periods.duration*7)) > .75
GROUP BY groups.id
To list all groups with at least one customer having at least one pickup due according to your calculation and it shows how many customers have a pickup due use the following
IF you want all groups listed including those not having any pickups use