2017-08-07 12 views
0

フィーチャーのオン/オフを追跡するテーブルactionがあるとします。フィールドはuser_idstatus( "オン" または「オフ)、datetimeある。さらにUnion allとSelection

、ユーザに関する履歴データを保持するテーブルuser_statusがある。フィールドはuser_idstatusdatetimeある。

ユーザーは今まであなたが過去のデータに現在のデータを追加するにはどうすればよいですか?上の機能を有効にしているどのように多くのユーザー?

GIある一つの答えは?今日で機能を有効どのように多くの質問。 venは次のとおりです:

select count(distinct(user_id)) from action 
where status = "on" and date = today() 

しかし、これは前の日の "on"のステータスを既に持っている人も含まれているようです。指定され

別の答えは次のとおりです。

create table total as 
(select us.user_id, today(), us.status 
    from 
    (select user_id, status, date 
    from user_status 
    where date = today()-1) us 

    left outer join 

    (select user_id, status, date, max(time) 
    from action 
    where date = today() 
    group by user_id, status) ts on us.user_id = ts.user_id 
    where ts.user_id is null 

    union all 

    select user_id, today(), status 
    from 
    (select user_id,status, max(time) 
    from action 
    where date = today() 
    group by user_id, status) a 

    union all 

    select * from user_status) 

これは昨日と昨日から異なるアクションを持っていたユーザーと同じ地位を持っていたユーザーの両方を考慮しているようですか?これは基本的に今日のデータを過去のデータに追加しますか?次に、最初の2つの質問に次のように答えてください:

select count(distinct(user_id)) from total 
where status = "on" and date = today() 

select count(distinct(user_id)) from total 
where status = "on" 

これが正しいでしょうか?

+0

予想される出力、表データをテキストとして追加してください。 – TheGameiswar

+0

@TheGameiswar:なし。面接の質問だった。 – Trevor

+0

質問を改善する方法の詳細については、このリンクをご覧ください:https://spaghettidba.com/2015/04/24/how-to-post-at-sql-question-on-a-public-forum/ – TheGameiswar

答えて

0
select 
count(distinct (case when status="on" and date=today() then user_id else null end)) as current, 
count(distinct (case when status="on" and date<today() then user_id else null end)) as previous 
from action 
関連する問題