按日期统计
代码:
-- 按年统计 SELECT YEAR(`date_field`), COUNT(*) AS `total` FROM `table` GROUP BY YEAR(`date_field`) -- 按年月统计 SELECT YEAR(`date_field`), MONTH(`date_field`), COUNT(*) AS `total` FROM `table` GROUP BY YEAR(`date_field`), MONTH(`date_field`) -- 按年月日统计 SELECT YEAR(`date_field`), MONTH(`date_filed`), COUNT(*) AS `total` FROM `table` GROUP BY YEAR(`date_field`), MONTH(`date_field`), DAY(`date_field`)
一个字段不同的统计条件
使用 CASE 关键字
代码:
/* 我需要按月统计完成的订单中客户给5星评价和给4星评价的数目*/ SELECT YEAR(`finishtime`), MONTH(`finishtime`), (CASE WHEN `rate`=5 THEN 1 ELSE NULL END), (CASE WHEN `rate`=4 THEN 1 ELSE NULL END), FROM `order` GROUP BY YEAR(`finishtime`), MONTH(`finishtime`)