Mysql按时,天,月,年统计数据 - [ 挑战者 ]

为了更加直观地观察数据的变化情况,我们经常需要对数据进行统计,制作折线图,饼图,直方图,来观察数据在一段时间的变化,方便我们做出策略性地调整。
次数的统计是最常见的一种,可以观察数据在一段时间内的变化,但也有多种需求,如观察每小时数据的变化,每天数据的变化,每月数据变化,每年数据的变化。
如下图:

但是如何设计一种方案来处理不同时间的变化呢?
我们应该尽可能地利用数据库的基本功能来完成这些功能,因为效率更加高。

1.把时间进行分组(不同类型分组不同)

时间戳方式:

  • 按照小时分组
    Select count(*) as count,date_format(FROM_UNIXTIME(createtime),’%Y-%m-%d %H’) as createdate from xtable group by createdate
  • 按照天分组
    Select count(*) as count,date_format(FROM_UNIXTIME(createtime),’%Y-%m-%d’) as createdate from xtable group by createdate
  • 按照天分组
    Select count(*) as count,date_format(FROM_UNIXTIME(createtime),’%Y-%m’) as createdate from xtable group by createdate
  • 按照年分组
    Select count(*) as count,date_format(FROM_UNIXTIME(createtime),’%Y’) as createdate from xtable group by createdate

    日期时间格式(标准)

  • 按照小时分组Select count(*) as count,date_format(createtime,’%Y-%m-%d %H’) as createdate from xtable group by createdate
  • 按照天分组
    Select count(*) as count,date_format(createtime,’%Y-%m-%d’) as createdate from xtable group by createdate
  • 按照天分组
    Select count(*) as count,date_format(createtime,‘%Y-%m’) as createdate from xtable group by createdate
  • 按照年分组
    Select count(*) as count,date_format(createtime,’%Y’) as createdate from xtable group by createdate

    2.多种类型数据的统计

    我们统计数据经常统计一种数据,一般有多种类型,如中国的人口=农村人口+城市人口
    这种情况要如何处理,才更加合理?假如先统计总数,再分别统计子项目数量,这样子当某个子项目数量为0时,统计就会出错。
    我们可以先统计出总的数据,如某段时间的中国人口数量变化,根据总数的日期(createdate )逐个查出农村和城市数量,这样就不会统计出不需要的数据。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章