ここexists
を使用して一つの方法である:
select count(*) as April_Creates,
sum(case when exists (select 1
from logins l2
where l2.user_id = u.user_id and
l2.create_date >= '2016-05-01' and l2.create_date < '2016-06-01'
)
then 1 else 0
end) as May_Logins
from users u
where u.create_date >= '2016-04-01' and u.create_date < '2016-05-01' and
exists (select 1
from logins l
where l.user_id = u.user_id and
l.create_date >= '2016-04-01' and l.create_date < '2016-05-01'
);
代替方法は、条件付きの集約を使用しています。
select sum(apr_login) as num_apr_logins,
sum(may_login) as num_may_logins,
sum(may_login)/1.0 * sum(may_login) as ratio
from users u join
(select user_id,
max(case when l.create_date >= '2016-04-01' and l.create_date < '2016-05-01'
then 1 else 0
end) as apr_login,
max(case when l.create_date >= '2016-05-01' and l.create_date < '2016-06-01'
then 1 else 0
end) as may_login
from logins l
group by user_id
having apr_login = 1
) l
where u.create_date >= '2016-04-01' and u.create_date < '2016-05-01' ;
残念ですが、ユーザーテーブルのレコードは一意ですが、ユーザーはログインテーブルに多数のインスタンスを持つことができます。あなたの最初の方法を使用して、私は一度ユーザーを数えるだけですか? @Cletus。 – Cletus
。 。最初のクエリは 'users'テーブルからのみ選択するので、重複するユーザは存在しません。 –