tags:

views:

37

answers:

3

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?

+3  A: 

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(), INTERAVAL 180 DAY)

...which means defining a GROUP BY clause.

OMG Ponies
@OMG Ponies: Thank you :)
SnOrfus
A: 

You may use a having clause for this:

SELECT 
person.id, 
person.phonenumber, 
MAX(activity.activitydate) as ndate
FROM 
person INNER JOIN activity ON person.id = activity.personid
GROUP BY person.id
HAVING MAX(activity.activitydate) < DATE_SUB(CURDATE(), INTERVAL 180 DAY)
Vincent Ramdhanie
A: 

Depending on the size of your dataset/indexing you might also look at using "TOP 1" with an ORDER BY vs "MAX". TOP 1 is occasionally faster on dates.

jasonk
I was actually having that conversation with someone yesterday, but his problem is that he wants a set of the `MAX()` values per user, not per query e.g. `SELECT MAX(activity.activitydate)`. His original query is only hypothetical, and not valid.
Marc Bollinger
`TOP 1` is SQL Server syntax - for MySQL, the synonym would be `LIMIT 1`.
OMG Ponies
Good catch OMG Ponies
jasonk