Min, Max, Group By and DateDiff
I'm trying to optimise many MySQL statements into one but have come across a problem.
MySQL query:
SELECT companyid, COUNT(*) AS total
FROM timesheet
WHERE userId='1'
AND DATEDIFF(MIN(startDate), MAX(endDate)) <= 77
GROUP开发者_开发知识库 BY companyid
HAVING total = 11
What I'm trying to do is select all companies where exactly 11 records exist and the first and last records were created within 11 weeks of each other. The error I get is "Invalid use of group function".
This is to do with the MIN(), MAX()
and DATEDIFF()
part but I can't for the life of me figure it out!
Aggregate functions needs to be in the HAVING clause, not the WHERE clause. (eg your DATEDIFF(MIN(startDate), MAX(endDate)) <= 77
condition)
Think of HAVING as applying to grouped records, and WHERE applying to individual records before being grouped.
精彩评论