在sql中每月统计新用户数

xxls0lw8  于 2021-07-24  发布在  Java
关注(0)|答案(3)|浏览(834)

我试图统计今年每个月记录的新用户数。喜欢
需要按月注册新用户的数据

JAn  Feb  Mar  April May ..... Dec

1     2   4     2     5 .....  1

通过创建日期和用户id。
这是用户表

id     created_at
1      2020-01-09 22:38:55
2      2020-02-09 22:38:55
3      2020-02-09 22:38:55
4      2020-03-09 22:38:55
5      2020-03-09 22:38:55
6      2020-03-09 22:38:55
7      2020-04-09 22:38:55
8      2020-04-09 22:38:55
9      2020-05-09 22:38:55

我正在尝试这个查询

SELECT  ut.id, Month(FROM_UNIXTIME(ut.created_at)), Count(*) 
from  $userTable ut 
where FROM_UNIXTIME(ut.created_at) >= CURDATE() - INTERVAL 1 YEAR
GROUP BY Month(FROM_UNIXTIME(ut.created_at));
ncgqoxb0

ncgqoxb01#

select中使用的所有非聚合函数的列都需要分组,ut.id不是group,在您的情况下,应该从select中删除
尝试

SELECT  Month(FROM_UNIXTIME(ut.created_at)), Count(*) from  $userTable ut 
where FROM_UNIXTIME(ut.created_at) >= CURDATE() - INTERVAL 1 YEAR
GROUP BY Month(FROM_UNIXTIME(ut.created_at));
ubbxdtey

ubbxdtey2#

如果要混合过去12个月的今年和去年的数据,可以使用:

SELECT SUM(MONTH(FROM_UNIXTIME(ut.created_at)) = 1) AS Jan,
       SUM(MONTH(FROM_UNIXTIME(ut.created_at)) = 2) AS Feb,
       SUM(MONTH(FROM_UNIXTIME(ut.created_at)) = 3) AS Mar,
       SUM(MONTH(FROM_UNIXTIME(ut.created_at)) = 4) AS Apr,
       SUM(MONTH(FROM_UNIXTIME(ut.created_at)) = 5) AS May,
       SUM(MONTH(FROM_UNIXTIME(ut.created_at)) = 6) AS Jun,
       SUM(MONTH(FROM_UNIXTIME(ut.created_at)) = 7) AS Jul,
       SUM(MONTH(FROM_UNIXTIME(ut.created_at)) = 8) AS Aug,
       SUM(MONTH(FROM_UNIXTIME(ut.created_at)) = 9) AS Sep,
       SUM(MONTH(FROM_UNIXTIME(ut.created_at)) = 10) AS Oct,
       SUM(MONTH(FROM_UNIXTIME(ut.created_at)) = 11) AS Nov,
       SUM(MONTH(FROM_UNIXTIME(ut.created_at)) = 12) AS Dec
FROM ut
WHERE FROM_UNIXTIME(ut.created_at) >= CURDATE() - INTERVAL 1 YEAR

注:假设 FROM_UNIXTIME() 实际上是必要的。它还使用一个方便的mysql快捷方式进行条件聚合。

agxfikkp

agxfikkp3#

您可以按年份分组,按月份求和,如下所示:

select YEAR(created_at) as year,
  sum(case when Month(created_at) = 1 then 1 else 0 end) AS Jan,
  sum(case when Month(created_at) = 2 then 1 else 0 end) AS Feb,
  sum(case when Month(created_at) = 3 then 1 else 0 end) AS Mar,
  sum(case when Month(created_at) = 4 then 1 else 0 end) AS Apr,
  sum(case when Month(created_at) = 5 then 1 else 0 end) AS May,
  sum(case when Month(created_at) = 6 then 1 else 0 end) AS Jun,
  sum(case when Month(created_at) = 7 then 1 else 0 end) AS Jul,
  sum(case when Month(created_at) = 8 then 1 else 0 end) AS Aug,
  sum(case when Month(created_at) = 9 then 1 else 0 end) AS Sep,
  sum(case when Month(created_at) = 10 then 1 else 0 end) AS Oct,
  sum(case when Month(created_at) = 11 then 1 else 0 end) AS Nov,
  sum(case when Month(created_at) = 12 then 1 else 0 end) AS Dec from ut group by YEAR(created_at)

相关问题