Mysql计数总和按月分组

时间:2015-05-21 14:51:42

标签: mysql

手头有非常棘手的问题。 我如何计算由此提供的用户总数。

SELECT 
MONTH(VisitTime) AS mon, 
COUNT( distinct IP) AS usersbymonth
FROM stats 
WHERE 
YEAR( VisitTime) = YEAR(  current_date  )  
GROUP BY mon
值得注意的是,汇总和计数(不同的IP)提供的更低 数(全年不同)。那是因为GROUP BY mon允许在多个月内存在相同的IP。

现在结果显示基本正确。月号| usersbymonth,如果您执行去年定位的查询,那么用户将在月前获得12个月的结果。

那么我如何计算用户数量和单位数总和?

1 个答案:

答案 0 :(得分:1)

我是对的吗?

SELECT mon, SUM(usersbymonth) FROM 
  (SELECT 
  MONTH(VisitTime) AS mon, 
  COUNT( distinct IP) AS usersbymonth
  FROM stats 
  WHERE 
  YEAR( VisitTime) = YEAR(  current_date  )  
  GROUP BY mon)

如果您想要每个月添加GROUP BY mon    的更新

  SELECT 
      MONTH(VisitTime) AS mon, 
      COUNT( distinct IP) AS usersbymonth
  FROM stats 
  WHERE 
      YEAR( VisitTime) = YEAR(  current_date  )  
  GROUP BY mon
  UNION -- Last ROW
  SELECT mon, SUM(usersbymonth) FROM (
    SELECT 
      MONTH(VisitTime) AS mon, 
      COUNT( distinct IP) AS usersbymonth
    FROM stats 
    WHERE 
      YEAR( VisitTime) = YEAR(  current_date  )  
    GROUP BY mon)