在查询中获得最常见的价值

时间:2017-03-22 16:18:33

标签: sql

我有一个表,其中用户执行具有多个不同选项的操作。我想搞清楚

  1. 100位用户执行了最多操作
  2. 对于100个用户中的每一个,什么     最常见的行动选择是
  3. 到目前为止,我的第一部分已经找到了:

    select a.user_id, count(a.id)
    from actions a
    group by a.user_id
    having count(*) > 1
    order by count(a.id) desc
    limit 100
    

    这为我提供了100个最活跃的用户。如何修改此选项以获取最常见的不同type操作?

1 个答案:

答案 0 :(得分:0)

假设type是您的行为并使用与您类似的语言:

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

假设您在SQL Server中使用正确的语法和更高的效率:

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