在不使用临时表的情况下将两个查询合并为一个

时间:2015-10-29 00:49:00

标签: mysql sql

我有工作结果,但我想知道是否可以将这些组合成一个查询而无需创建临时表:

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`;

1 个答案:

答案 0 :(得分:1)

这是你想要的吗?它使所有用户在一个月内登录的时间少于20天,当他们至少登录一次时:

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;