【发布时间】:2020-07-21 04:06:15
【问题描述】:
我有一个 SQL 查询,它按天计算特定 group 用户的用户吸收(注册)。它还进行累积(运行总计)
select Date, Cumulative, Up as Uptake
from (
select Date, Up, @running_total:=@running_total + Up as Cumulative
from (
select distinct(date(`audit`.`created_at`)) as Date, COALESCE(f.uptake, 0) as Up
from `audit`
left join (
select date(`users`.`created_at`) as day, count(`users`.`id`) as uptake
from `users`
where `users`.`group_uuid` = (select `groups`.`uuid` from `groups` where `groups`.`name` = "companyA")
group by day
) f on f.day = date(`audit`.`created_at`)
where `audit`.`created_at` between '2019-07-03' and CURDATE()
) c
JOIN (SELECT @running_total:=0) r
) final
order by Date desc
这个查询使用audit 表纯粹是为了让我得到一个可靠的日期列表,即使每天都没有创建用户,我知道audit 表有记录。
我可以通过
轻松获得所有组select `groups`.`name` from `groups`
我想要的是......每天一个条目和一个组与吸收(如果可能的话,累积) 示例:
Date | Cumulative | Uptake | group
2020-04-07 | 2 | 1 | comapnyA
2020-04-07 | 5 | 3 | comapnyB
2020-04-06 | 1 | 0 | comapnyA
2020-04-06 | 2 | 1 | comapnyB
2020-04-05 | 1 | 1 | comapnyA
2020-04-05 | 1 | 1 | comapnyB
.... etc
【问题讨论】:
-
专业提示:使用表名或(甚至更好)短表别名来限定所有列引用。此外,DISTINCT 是关键字,而不是函数。在 SELECT 列表中,它适用于 SELECT 列表中的所有表达式,允许使用不必要的括号但不会改变行为,所以不要添加虚假的括号。
标签: mysql sql date group-by count