Ok, i have a database in which i have all my users registered with their datetime
which stores in my MYSQL datetime field as 2012-03-31 12:13:42
now i want to fetch COUNT
of users according to year
and month
.
As i want to present a chart data for that purpose, i want total customers added in January
, in feb
, march
and so on.... in particular year.
ie it has to be year specific
that in 2010
Jan
lets say 52 Customers in 2010
Feb
lets say 72 Customers .
Note : The query i want to execute is using PHP and Mysql.
You can use the MySQL date functions
SELECT YEAR(date_field) as stat_year,
MONTH(date_field) as stat_month,
COUNT(*) as stat_count
FROM `table`
GROUP BY stat_year,stat_month
If you only want the results for a specific year/month, you can add conditions to the WHERE clause (and remove the GROUP BY) like this
SELECT COUNT(*) as stat_count
FROM `table`
WHERE YEAR(date_field) = 2012
AND MONTH(date_field) = 3
There are different SQL that will do the trick, here is one ...
SELECT COUNT(dt), DATE_FORMAT(dt, '%Y-%b') AS df FROM foo GROUP BY df;
where foo is your table name, and dt is the datetime column. Note that this will apply the function DATE_FORMAT on each row. Also, you can change the format as desired, eg use %m for numeric month, %M for full month name, etc. Add in where clause to filter as needed. The following SQL is almost the same ...
SELECT COUNT(dt), YEAR(dt) AS y, MONTH(dt) AS m FROM foo GROUP BY y, m;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.