【问题标题】:mysql count and then group by that countmysql 计数,然后按该计数分组
【发布时间】:2016-11-26 08:52:59
【问题描述】:

我有一个结构如下的表格:

user_id   saved_id
1         2
1         34
1         36
2         489
2         14
3         731
4         48
5         901
6         234
6         9
6         64

我想做的是首先计算每个用户有多少保存的 id,然后对这些结果进行分组,以便我知道每个 total_saves 发生的频率。

这是我目前拥有的:

SELECT user_id, count(*) as total_saves FROM table GROUP BY user_id ORDER BY total_saves DESC

这给了我

user_id   total_saves
1         3
6         3
2         2
3         1
4         1
5         1

我想要的是这样的:

total_saves   count
3             2
2             1
1             3

我不知道如何对我已经拥有的 total_saves 进行分组。我试过GROUP BY total_saves 但这不起作用。

【问题讨论】:

    标签: mysql sql sql-server group-by aggregation


    【解决方案1】:

    使用两个聚合:

    select total_saves, count(*) as cnt
    from (select user_id, count(*) as total_saves
          from t
          group by user_id
         ) t
    group by total_saves;
    

    【讨论】:

      【解决方案2】:

      使用子查询

      select total_saves, count(total_saves) as count
      from (select user_id, count(*) as total_saves
        from table
        group by user_id
       ) a
      group by total_saves order by total_saves;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-22
        • 2018-04-06
        • 1970-01-01
        • 1970-01-01
        • 2012-05-10
        • 1970-01-01
        相关资源
        最近更新 更多