Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql-具有唯一订户用户的按月分组。用户不应重复_Mysql_Sql_Group By_Unique_Distinct - Fatal编程技术网

Mysql-具有唯一订户用户的按月分组。用户不应重复

Mysql-具有唯一订户用户的按月分组。用户不应重复,mysql,sql,group-by,unique,distinct,Mysql,Sql,Group By,Unique,Distinct,下表列出了所有订户用户。我想要每月唯一的订户用户组,但如果用户已经订阅,则不应在计数中重复 ID | USER | CREATED DATE 1 | 1 | 2019-10-16 2 | 2 | 2019-10-18 3 | 3 | 2019-12-06 4 | 2 | 2020-01-01 (* This is repeated so should not be count in 01) 5 | 4 | 2020-01-05 6

下表列出了所有订户用户。我想要每月唯一的订户用户组,但如果用户已经订阅,则不应在计数中重复

ID | USER   | CREATED DATE
1  | 1      | 2019-10-16
2  | 2      | 2019-10-18
3  | 3      | 2019-12-06
4  | 2      | 2020-01-01 (* This is repeated so should not be count in 01)
5  | 4      | 2020-01-05
6  | 5      | 2020-01-11
7  | 1      | 2020-02-14 (* This is repeated so should not be count in 02)
8  | 2      | 2020-03-06 (* This is repeated so should not be count in 03)
9  | 5      | 2020-03-15 (* This is repeated so should not be count in 03)
我的预期输出应该如下所示。总用户数为5,因此总用户数之和必须为5

TOTAL   | MONTH
2       | 10
1       | 12
2       | 01
0       | 02
0       | 03

使用
分组依据
获取第一个月,然后再次聚合:

select year(min_cd), month(min_cd), count(*)
from (select user, min(created_date) as min_cd
      from t
      group by user
     ) u
group by year(min_cd), month(min_cd);
这不包括
0
值,但它们似乎有些武断

如果确实希望将它们与数据一起使用,则一种方法是窗口函数和条件聚合:

select year(min_cd), month(min_cd),
       sum( min_cd = created_date )
from (select user, min(created_date) over (partition by user) as min_cd
      from t
     ) u
group by year(min_cd), month(min_cd);

第二个查询抛出一个错误代码:1064。您的SQL语法有错误;查看与您的MySQL服务器版本相对应的手册,了解使用near'(按订阅者划分的用户id)作为min_cd from t t)u group by year('在第行)的正确语法3@Ruchi…MySQL 8.0支持启动窗口功能。