I'm trying to write a sql function to do something like:
SELECT
    person.id, 
    person.phonenumber
FROM
    person INNER JOIN activity ON person.id = activity.personid
WHERE
    MAX(activity.activitydate) < DATE_SUB(CURDATE(), INTERAVAL 180 DAY);
Each time a person is contacted, we create an activity record for them with notes and the like. So I'm looking for all of the people, who haven't been contacted in the last 180 days. Obviously, this doesn't work, as max can't be used in the where clause.
I saw this, but mysql doesn't have the with statement.
Additionally, I tried
SELECT 
    person.id, 
    person.phonenumber, 
    MAX(activity.activitydate) as ndate
FROM 
    person INNER JOIN activity ON person.id = activity.personid
WHERE 
    ndate < DATE_SUB(CURDATE(), INTERVAL 180 DAY)
GROUP BY person.id;
but ndate wasn't known.
Any idea how I'd do this?
You need to use the HAVING clause:
  SELECT p.id, 
         p.phonenumber
    FROM PERSON p 
    JOIN ACTIVITY a ON a.personid = p.id
GROUP BY p.id, p.phonenumber
  HAVING MAX(a.activitydate) < DATE_SUB(CURDATE(), INTERVAL 180 DAY)
...which means defining a GROUP BY clause.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With