我有工作结果,但我想知道是否可以将这些组合成一个查询而无需创建临时表:
CREATE TEMPORARY TABLE IF NOT EXISTS monthlytables AS (select user as "user", date_format(begin_time, '%Y-%m') as "date", count(distinct date(begin_time)) as "sessions" from user_session group by user_id, month(begin_time) having count(distinct date(begin_time)) < 15 order by date_format(begin_time, '%Y-%m'));
select `date`,count(`date`) from monthlytables group by `date`;
答案 0 :(得分:1)
select user month(begin_session), count(distinct date(begin_session))
from atable t
group by user, month(begin_session)
having count(distinct date(begin_session)) < 20;
如果您想要特定月份的此信息,请添加where
条款。
编辑:
如果您想按月计算,只需将其用作子查询:
select mon, sum(cnt < 20) as num
from (select user, month(begin_session) as mon,
count(distinct date(begin_session)) as cnt
from atable t
group by user, month(begin_session)
) t
group by mon;