2017-03-22 14 views
-1

ユーザーがいくつかの異なるオプションを持つアクションを実行するテーブルがあります。私は100人のユーザーがアクションの最も一般的なオプションだった行って何 最もアクション100人のユーザーのそれぞれについて、 クエリ内で最も一般的な値を取得する

  • はこれまでのところ、私が持っているを行っている

    1. 把握したいです最初の部分を見つけた:

      これは私に100人の最もアクティブなユーザーを与えます。最も一般的な異なるtypeのアクションを取得するには、これをどのように変更できますか?

    +1

    DBMSがありますあなたは使っていますか? (いくつかの非ANSI SQLがあります...) – jarlh

    +0

    'Group By [actionName]'だけを選択してください - アクション名またはタイプの列名が何であってもグループ化してください。 – TheUknown

    答えて

    0

    typeがあなたの行動であると仮定するとあなたに似た言語を使用して:あなたは正しい構文を使用してSQL Serverでいると仮定すると、

    Select au.user_id, au.total_actions, at.type, at.nb_of_type 
    
    From  (select user_id, count(id) as total_actions 
           from actions 
           group by type 
           having count(*) > 1 
           order by count(id) desc 
           limit 100) As au -- ActiveUser 
    
    Inner join (select user_id, type, MAX(count(a.id)) as nb_of_type 
           from action 
           group by user_id, type) As at -- ActiveType 
    
    On at.user_id = au.user_id 
    

    と優れた効率:

    WITH ActiveUser (user_id, total_actions) 
    AS 
    (
        select top 100 user_id, count(id) 
        from actions 
        group by type 
        order by count(id) desc 
    ) 
    
    Select au.user_id, au.nb_total_of_actions, t.type, t.nb_of_type 
    From ActiveUser au 
    Inner join (select user_id, type, MAX(count(id)) as nb_of_type 
           from action 
           group by user_id, type 
           where user_id in (Select user_id from ActiveUser) 
          ) at -- ActiveType 
    On at.user_id = au.user_id 
    
    関連する問題