Is it possible to make a simple query to count how many records I have in a determined period of time like a year, month, or day, having a TIMESTAMP
field, like
GROUP BY YEAR(record_date), MONTH(record_date)
Check out the date and time functions in MySQL.
I prefer to optimize the one year group selection like so:
SELECT COUNT(*)
FROM stats
WHERE record_date >= :year
AND record_date < :year + INTERVAL 1 YEAR;
This way you can just bind the year in once, e.g. '2009'
, with a named parameter and don't need to worry about adding '-01-01'
or passing in '2010'
separately.
Also, as presumably we are just counting rows and id
is never NULL
, I prefer COUNT(*)
to COUNT(id)
.
.... group by to_char(date, 'YYYY')
--> 1989
.... group by to_char(date,'MM')
-->05
.... group by to_char(date,'DD')
--->23
.... group by to_char(date,'MON')
--->MAY
.... group by to_char(date,'YY')
--->89
If you want to group by date in MySQL then use the code below:
SELECT COUNT(id)
FROM stats
GROUP BY DAYOFMONTH(record_date)
Hope this saves some time for the ones who are going to find this thread.
Complete and simple solution with similarly performing yet shorter and more flexible alternative currently active:
SELECT COUNT(*) FROM stats
-- GROUP BY YEAR(record_date), MONTH(record_date), DAYOFMONTH(record_date)
GROUP BY DATE_FORMAT(record_date, '%Y-%m-%d')
I tried using the 'WHERE' statement above, I thought its correct since nobody corrected it but I was wrong; after some searches I found out that this is the right formula for the WHERE statement so the code becomes like this:
SELECT COUNT(id)
FROM stats
WHERE YEAR(record_date) = 2009
GROUP BY MONTH(record_date)