简体   繁体   English

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

[英]MySql: Count occurrences of distinct values by date

I am trying to find a MySQL query that will find distinct values in a particular field (ID) with a specific date, and then count the number of occurrences of that value and separate it by date.我试图找到一个 MySQL 查询,它将在具有特定日期的特定字段 (ID) 中找到不同的值,然后计算该值的出现次数并按日期分隔。 See example below:请参阅下面的示例:

example 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

expected output预期产出

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

this query这个查询

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

gives me these results:给我这些结果:

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

but it wont provide data for month 2但它不会提供第 2 个月的数据

What am I missing here?我在这里缺少什么?

You are missing group by and aggregation functions:您缺少group by和聚合函数:

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

As a note.作为笔记。 I think it is better to put year-month combinations in the YYYYMM format.我认为最好将年月组合放在 YYYYMM 格式中。 This makes it nicer to sort the data.这样可以更好地对数据进行排序。 You can write this as:你可以这样写:

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

In fact, you could just leave it as two columns:实际上,您可以将其保留为两列:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM