MySql:按日期计算不同值的出现次数

时间:2015-02-01 22:03:12

标签: mysql

我正在尝试查找一个MySQL查询,该查询将在特定字段(ID)中查找具有特定日期的不同值,然后计算该值的出现次数并按日期分隔。见下面的例子:

示例db

id         Date                    ID
-----      ------                  -------
1          2015-01-24 14:13:50     user1
2          2015-01-24 14:13:50     user1
3          2015-01-24 14:13:50     user2
4          2015-01-24 14:13:50     user2
5          2015-02-24 04:13:50     user2
6          2015-02-24 04:13:50     user1
7          2015-02-24 04:13:50     user3

预期产出

month        uniqueUsers
---------    ----------
12015        2
22015        3

此查询

SELECT DISTINCT CONCAT( MONTH(  `Date` ) , YEAR(  `Date` ) ) AS 
MONTH ,  COUNT( DISTINCT  `ID` )  AS uniqueUsers
FROM  `myDB` 

给了我这些结果:

month        uniqueUsers
---------    ----------
12015        2

但它不会提供第2个月的数据

我在这里缺少什么?

1 个答案:

答案 0 :(得分:3)

您缺少group by和聚合函数:

SELECT CONCAT(MONTH(`Date) , YEAR(`Date`)) AS MYYYY , 
       COUNT(DISTINCT ID) as NumUsers
FROM  `myDB` 
GROUP BY CONCAT(MONTH(`Date`), YEAR(`Date`) )

作为一个说明。我认为最好将年月组合放在YYYYMM格式中。这样可以更好地对数据进行排序。你可以这样写:

SELECT DATE_FORMAT(`Date`, '%Y-%m') as YYYYMM, COUNT(DISTINCT ID) as NumUsers
FROM  `myDB` 
GROUP BY YYYYMM
ORDER BY YYYYMM;

事实上,您可以将其保留为两列:

SELECT YEAR(`Date`) as YYYY, MONTH(`Date`) as MM,
       COUNT(DISTINCT ID) as NumUsers
FROM  `myDB` 
GROUP BY YYYY, MM
ORDER BY YYYY, MM;