SELECT DATE_FORMAT(ec_salesorder.duedate,’%Y-%m’) as m, sum(ec_salesorder.total) as total, count(*) as so_count FROM ec_salesorder GROUP BY m ORDER BY m,也就是把duedate日期以月的形式显示,然后groupby,那么按周如何统计呢?
搜了一下mysql的manual,在这里找到一个解决方法,通过mysql的week函数来做,sql语句如下:SELECT WEEK(ec_salesorder.duedate) as m, sum(ec_salesorder.total) as total, count(*) as so_count FROM ec_salesorder GROUP BY m ORDER BY m,这个方法有个缺陷,不能显示年份,仅仅靠一个周数不方便查看统计信息。
继续研究mysql manual,在DATE_FORMAT函数介绍发现2个格式符和周有点关系:
%X Year for the week where Sunday is the first day of the week, numeric, four digitsused with %V
%x Year for the week, where Monday is the first day of the week, numeric, four digitsused with %v
把上面的Sql语句中改成:
SELECT DATE_FORMAT(ec_salesorder.duedate,’%x %v’) as m, sum(ec_salesorder.total) as total, count(*) as so_count FROM ec_salesorder GROUP BY m ORDER BY m
显示的结果如下:
m total so_count
2009 11 10000.00 3
2009 12 44000.00 5
如果周日为一周的第一天,那么sql语句应该为:
SELECT DATE_FORMAT(ec_salesorder.duedate,’%X %V’) as m, sum(ec_salesorder.total) as total, count(*) as so_count FROM ec_salesorder GROUP BY m ORDER BY m
结果应该没错,不出意外,易客CRM下个版本将增加按周统计销售情况的报表。
让groupby使用索引而不创建临时表,使用索引的前提条件是:所有GROUPBY列引用同一索引的属性,并且索引按顺序保存其关键字(B-树索引,不是HASH索引)至于DISTINCT和GROUPBY哪个效率更高?理论上DISTINCT *** 作只需要找出所有不同的值就可以了。而GROUPBY *** 作还要为其他聚集函数进行准备工作。从这一点上将,GROUPBY *** 作做的工作应该比DISTINCT所做的工作要多一些。但是实际上,DISTINCT *** 作,它会读取了所有记录GROUPBY需要读取的记录数量与分组的组数量一样多,比实际存在的记录数目要少很多。欢迎分享,转载请注明来源:内存溢出
评论列表(0条)