views:

82

answers:

2

I'm using MySQL and I have the following table:

| clicks | int  |
|   period  | date |

I want to be able to generate reports like this, where periods are done in the last 4 weeks:

|   period    | clicks |
|  1/7 - 7/5  |  1000  | 
| 25/6 - 31/7 |  ....  |
| 18/6 - 24/6 |  ....  |
| 12/6 - 18/6 |  ....  |

or in the last 3 months:

| period | clicks |
|  July  |  ....  |
|  June  |  ....  |
| April  |  ....  |

Any ideas how to make select queries that can generate the equivalent date range and clicks count?

+3  A: 

For the last 3 months you can use:

SELECT MONTH(PERIOD), SUM(CLICKS)
FROM TABLE
WHERE PERIOD >= NOW() - INTERVAL 3 MONTH
GROUP BY MONTH(PERIOD)

or for the last 4 weeks:

SELECT WEEK(PERIOD), SUM(CLICKS)
FROM TABLE
WHERE PERIOD >= NOW() - INTERVAL 4 WEEK
GROUP BY WEEK(PERIOD)

Code not tested.

Keeper
I don't know if the optimizer works with WEEK(Period) without checking all the dates in the result. That's why I like to use WEEK(Period) AS WeekPeriod, Group by WeekPeriod
simendsjo
I use mainly Oracle for which you have to group by the same field you select (you can't alias a field and group by that).I think internally the query is the same.
Keeper
+1  A: 
SELECT
 WEEKOFYEAR(`date`) AS period,
 SUM(clicks) AS clicks
FROM `tablename`
WHERE `date` >= CURDATE() - INTERVAL 4 WEEK
GROUP BY period

SELECT
 MONTH(`date`) AS period,
 SUM(clicks) AS clicks
FROM `tablename`
WHERE `date` >= CURDATE() - INTERVAL 3 MONTH
GROUP BY period

simendsjo
That's a better check for the period, I corrected my answer to reflect it.
Keeper
Out of curiosity, how the queries should be if the period field is an integer like 20100609 which corresponds to 2010-06-09 date. Would the performance be better in such int type?
khelll
Probably only if you need to filter a range of dates because you can't filter by week (you still have to cast it as a date).And remember to choose an answer :P
Keeper
@khell: I wouldn't bother with such micro-optimalizations. I've done this a thousand times on large tables without any problems. Just make sure you are indexing the column.
simendsjo
I'm wondering if there is a way to the display the periods for the weekly report as mentioned in the question
khelll