【发布时间】:2021-11-24 11:04:39
【问题描述】:
我正在运行此查询以获取过去 3 个月内每个用户的平均登录次数。如果用户在最近 3 个月内登录过,则取其平均值,否则返回 0。
我尝试了多种不同的方法,但似乎如果用户在过去 3 个月内没有登录,则没有记录,并且 count() 不返回 0。它只是什么都不返回。
1) select case count(*)
WHEN 0
THEN 0
ELSE count(creationTS) / 3
END as average
from table_name where creationTS >= add_months(now(), -3)
and userId = '110'
group by userId;
2) select COALESCE(count(creationTS)/3,0) as average
from table_name where creationTS >= add_months(now(), -3)
and userId = '110'
group by userId;
如果找到条件“creationTS >= add_months(now(), -3)”的记录但不存在记录,则它会给出正确的结果,它不会返回任何内容。在那种情况下我怎么能返回 0。
【问题讨论】: