sql时间戳按月份聚合
emer 发布于 2019-4-9 10:04 3516 次阅读
create_time为时间格式(字段名create_time 根据自己表字段修改,数据库中存为201610071202)
SELECT DATE_FORMAT(create_time,'%Y%u') weeks,COUNT(id) COUNT FROM role GROUP BY weeks; SELECT DATE_FORMAT(create_time,'%Y%m%d') days,COUNT(id) COUNT FROM role GROUP BY days; SELECT DATE_FORMAT(create_time,'%Y%m') months,COUNT(id) COUNT FROM role GROUP BY months;
create_time为时间戳格式(字段名create_time 根据自己表字段修改,数据库中存为1474959640):
SELECT FROM_UNIXTIME(create_time,'%Y%u') weeks,COUNT(id) COUNT FROM role GROUP BY weeks; SELECT FROM_UNIXTIME(create_time,'%Y%m%d') days,COUNT(id) COUNT FROM role GROUP BY days; SELECT FROM_UNIXTIME(create_time,'%Y%m') months,COUNT(id) COUNT FROM role GROUP BY months;
mysql中本身支持一种更好的方法来达到上面的效果,那就是使用SQL_CALC_FOUND_ROWS和FOUND_ROWS()函数。见:http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_found-rows
应用举例:
mysql>
SELECT SQL_CALC_FOUND_ROWS * FROM
tbl_name
1
->
WHERE id > 100 LIMIT 10;
1
mysql>
SELECT FOUND_ROWS();