因此,有效地说,我想做的是通过计算当月的所有新用户减去上月的新用户来显示一个值,然后将增长除以上月的数字,再乘以100。这会增加百分比,但永远不会显示负数,我意识到使用abs((可以将负数转换为正数,这是一个允许我这样做的函数吗?
谢谢。
select round(abs
((select count(id) from users where
month(created_at) = month(current_date())
and
YEAR(created_at) = year(current_date()))
-
(select count(id) from users where
month(created_at) = month(current_date - interval 1 MONTH)
and
YEAR(created_at) = year(current_date - interval 1 MONTH)))
/
(select count(id) from users where
month(created_at) = month(current_date())
and
YEAR(created_at) = year(current_date()))
*100, 0)
as abs_diff
from users
limit 1
;
您可以使用获取当月的新用户数量
count(case when last_day(created_at) = last_day(current_date) then 1 end)
以及上个月的新用户数量:
count(case when last_day(created_at) = last_day(current_date - interval 1 month) then 1 end)
所以,把这些数字除以1,然后再乘以100:
select
100 * (
count(case when last_day(created_at) = last_day(current_date) then 1 end) /
nullif(count(case when last_day(created_at) = last_day(current_date - interval 1 month) then 1 end), 0)
- 1
) abs_diff
from users
where date(created_at) > last_day(current_date - interval 2 month)
如果上个月的新用户数为0
,则函数nullif()
将返回null
,以避免被0
除
查看简化的演示
我在想这样的事情:
select ym.*,
(this_month - last_month) * 100.0 / last_month
from (select year(created_at) as yyyy, month(created_at) as mm, count(*) as this_month,
lag(count(*)) over (order by min(created_at)) as prev_month
from users
group by yyyy, mm
) ym;
窗口函数是进行月度比较的更简单的方法。
如果你只想在本月使用,你可以添加:
order by yyyy desc, mm desc
limit 1