tags:

views:

36

answers:

1

I'm trying to write a query to work out how much commission that my client's company earns in a month as below

SELECT (rate * SUM(duration) / 180) as commission
        FROM   teacher, person, lesson 
        WHERE  person.id = teacher.person_id
        AND    lesson.teacher = person.id
        AND    MONTH(start_time) = MONTH(NOW())
        GROUP BY person.id

This is fine for working out this month, but how would I do this to give results for the past 12 months?

A: 

Use GROUP BY person.id, MONTH(start_time) and change the last AND clause in the WHERE into MONTH(NOW()) - MONTH(start_time) <= 12.

Alex Martelli
this is not good when there are several years in the database, but I get the idea
Robert
@Robert, it's equivalent to the `MONTH` check in the original -- if a `YEAR` check is needed here, it's also needed in the original. I do suspect you're in for a close-to-full-table scan in both cases (mysql can't use an index for computed expressions such as `MONTH(blah)`), but the only workaround, if that's indeed a problem, would be to denormalize the table (`lesson`, I assume) by adding a logically redundant `month` field and an appropriate composite index.
Alex Martelli